Python seaborn.set_palette() Examples
The following are 26
code examples of seaborn.set_palette().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
seaborn
, or try the search function
.
Example #1
Source File: plot_utils.py From celer with BSD 3-Clause "New" or "Revised" License | 7 votes |
def plot_path_hist(results, labels, tols, figsize, ylim=None): configure_plt() sns.set_palette('colorblind') n_competitors = len(results) fig, ax = plt.subplots(figsize=figsize) width = 1. / (n_competitors + 1) ind = np.arange(len(tols)) b = (1 - n_competitors) / 2. for i in range(n_competitors): plt.bar(ind + (i + b) * width, results[i], width, label=labels[i]) ax.set_ylabel('path computation time (s)') ax.set_xticks(ind + width / 2) plt.xticks(range(len(tols)), ["%.0e" % tol for tol in tols]) if ylim is not None: plt.ylim(ylim) ax.set_xlabel(r"$\epsilon$") plt.legend(loc='upper left') plt.tight_layout() plt.show(block=False) return fig
Example #2
Source File: analytics.py From openai_lab with MIT License | 6 votes |
def scoped_mpl_import(): import matplotlib matplotlib.rcParams['backend'] = MPL_BACKEND import matplotlib.pyplot as plt plt.rcParams['toolbar'] = 'None' # mute matplotlib toolbar import seaborn as sns sns.set(style="whitegrid", color_codes=True, font_scale=1.0, rc={'lines.linewidth': 1.0, 'backend': matplotlib.rcParams['backend']}) palette = sns.color_palette("Blues_d") palette.reverse() sns.set_palette(palette) return (matplotlib, plt, sns)
Example #3
Source File: callbacks.py From keras-utilities with MIT License | 6 votes |
def on_train_begin(self, logs={}): sns.set_style("whitegrid") sns.set_style("whitegrid", {"grid.linewidth": 0.5, "lines.linewidth": 0.5, "axes.linewidth": 0.5}) flatui = ["#9b59b6", "#3498db", "#95a5a6", "#e74c3c", "#34495e", "#2ecc71"] sns.set_palette(sns.color_palette(flatui)) # flatui = ["#9b59b6", "#3498db", "#95a5a6", "#e74c3c", "#34495e", "#2ecc71"] # sns.set_palette(sns.color_palette("Set2", 10)) plt.ion() # set plot to animated width = self.width * (1 + len(self.get_metrics(logs))) height = self.height self.fig = plt.figure(figsize=(width, height)) # move it to the upper left corner move_figure(self.fig, 25, 25)
Example #4
Source File: plotlib.py From mCaller with MIT License | 5 votes |
def plot_training_probabilities(prob_scores,tb): #prob_scores = {'m6A':[0.9,0.4,...],'A':[0.1,0.5,0.2,...]} sns.set_style('darkgrid') sns.set_palette(['#55B196','#B4656F']) fig = plt.figure(figsize=(3,4)) prob_dict = {'probability':prob_scores[base]+prob_scores[modbase],'base':[base]*len(prob_scores[base])+[modbase]*len(prob_scores[modbase])} prob_db = pd.DataFrame(prob_dict) sns.boxplot(x="base", y="probability", data=prob_db) sns.despine() plt.show() plt.savefig('training_probability_'+tb+'_model_boxplot.pdf',transparent=True,dpi=500,bbox_inches='tight')
Example #5
Source File: plot_utils.py From celer with BSD 3-Clause "New" or "Revised" License | 5 votes |
def configure_plt(): rc('font', **{'family': 'sans-serif', 'sans-serif': ['Computer Modern Roman']}) params = {'axes.labelsize': 12, 'font.size': 12, 'legend.fontsize': 12, 'xtick.labelsize': 10, 'ytick.labelsize': 10, 'text.usetex': True, 'figure.figsize': (8, 6)} plt.rcParams.update(params) sns.set_palette('colorblind') sns.set_context("poster") sns.set_style("ticks")
Example #6
Source File: LST.py From python-urbanPlanning with MIT License | 5 votes |
def histogramFig(self,x): sns.set_palette("hls") f, ax= plt.subplots(figsize = (20, 20)) sns.distplot(x, hist=False, color="r", kde_kws={"shade": True},ax=ax) ax.tick_params(labelsize=30) plt.show() ##箱型图
Example #7
Source File: simple.py From qstrader with MIT License | 5 votes |
def plot_results(self): """ A simple script to plot the balance of the portfolio, or "equity curve", as a function of time. """ sns.set_palette("deep", desat=.6) sns.set_context(rc={"figure.figsize": (8, 4)}) # Plot two charts: Equity curve, period returns fig = plt.figure() fig.patch.set_facecolor('white') df = pd.DataFrame() df["equity"] = pd.Series(self.equity, index=self.timeseries) df["equity_returns"] = pd.Series(self.equity_returns, index=self.timeseries) df["drawdowns"] = pd.Series(self.drawdowns, index=self.timeseries) # Plot the equity curve ax1 = fig.add_subplot(311, ylabel='Equity Value') df["equity"].plot(ax=ax1, color=sns.color_palette()[0]) # Plot the returns ax2 = fig.add_subplot(312, ylabel='Equity Returns') df['equity_returns'].plot(ax=ax2, color=sns.color_palette()[1]) # drawdown, max_dd, dd_duration = self.create_drawdowns(df["Equity"]) ax3 = fig.add_subplot(313, ylabel='Drawdowns') df['drawdowns'].plot(ax=ax3, color=sns.color_palette()[2]) # Rotate dates fig.autofmt_xdate() # Plot the figure plt.show()
Example #8
Source File: stats.py From temci with GNU General Public License v3.0 | 5 votes |
def reset_plt(self): """ Reset the current matplotlib plot style. """ import matplotlib.pyplot as plt plt.gcf().subplots_adjust(bottom=0.15) if Settings()["report/xkcd_like_plots"]: import seaborn as sns sns.reset_defaults() mpl.use("agg") plt.xkcd() else: import seaborn as sns sns.reset_defaults() sns.set_style("darkgrid") sns.set_palette(sns.color_palette("muted")) mpl.use("agg")
Example #9
Source File: graph.py From pipedream with MIT License | 5 votes |
def plot_cdfs(self, cdfs, output_directory): import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as plt from matplotlib.backends.backend_pdf import PdfPages import seaborn as sns matplotlib.rc('text', usetex=True) sns.set_style('ticks') sns.set_style({'font.family':'sans-serif'}) flatui = ['#002A5E', '#FD151B', '#8EBA42', '#348ABD', '#988ED5', '#777777', '#8EBA42', '#FFB5B8'] sns.set_palette(flatui) paper_rc = {'lines.linewidth': 2, 'lines.markersize': 10} sns.set_context("paper", font_scale=3, rc=paper_rc) current_palette = sns.color_palette() plt.figure(figsize=(10, 4)) ax = plt.subplot2grid((1, 1), (0, 0), colspan=1) labels = ["Compute", "Activations", "Parameters"] for i in range(3): cdf = [cdfs[j][i] for j in range(len(cdfs))] ax.plot(range(len(cdfs)), cdf, label=labels[i], linewidth=2) ax.set_xlim([0, None]) ax.set_ylim([0, 100]) ax.set_xlabel("Layer ID") ax.set_ylabel("CDF (\%)") plt.legend() with PdfPages(os.path.join(output_directory, "cdf.pdf")) as pdf: pdf.savefig(bbox_inches='tight')
Example #10
Source File: plot.py From pipedream with MIT License | 5 votes |
def plot(values, epochs_to_plot, ylimit, ylabel, output_filepath): import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as plt from matplotlib.backends.backend_pdf import PdfPages import seaborn as sns matplotlib.rc('text', usetex=True) sns.set_style('ticks') sns.set_style({'font.family':'sans-serif'}) flatui = ['#002A5E', '#FD151B', '#8EBA42', '#348ABD', '#988ED5', '#777777', '#8EBA42', '#FFB5B8'] sns.set_palette(flatui) paper_rc = {'lines.linewidth': 2, 'lines.markersize': 10} sns.set_context("paper", font_scale=3, rc=paper_rc) current_palette = sns.color_palette() plt.figure(figsize=(10, 4)) ax = plt.subplot2grid((1, 1), (0, 0), colspan=1) for epoch_to_plot in epochs_to_plot: values_to_plot = values[epoch_to_plot] ax.plot(range(len(values_to_plot)), values_to_plot, label="Epoch %d" % epoch_to_plot, linewidth=2) ax.set_xlim([0, None]) ax.set_ylim([0, ylimit]) ax.set_xlabel("Layer ID") ax.set_ylabel(ylabel) plt.legend() with PdfPages(output_filepath) as pdf: pdf.savefig(bbox_inches='tight')
Example #11
Source File: effectiveness.py From rankeval with Mozilla Public License 2.0 | 5 votes |
def init_plot_style(): """ Initialize plot style for RankEval visualization utilities. Returns ------- """ plt.style.use("seaborn-notebook") sns.set_palette("deep")
Example #12
Source File: action.py From insightconnect-plugins with MIT License | 5 votes |
def run(self, params={}): # Set styles sns.set_palette(params.get('color_palette')) sns.set(style=params.get('margin_style')) # Process the data and create the plot try: decoded_data = base64.b64decode(params.get('csv_data')) except Exception as e: error = f"Failed to decode base64 encoded CSV data with error: {e}" self.logger.error(error) raise e column = params.get('column') df = pd.read_csv(BytesIO(decoded_data)) if not column or (column not in df): error = f"Column ({column}) not found in data set, cannot create plot..." self.logger.error(error) return Exception(error) # AxesSubplots (the plot object returned) don't have the savefig method, get the figure, then save it self.logger.info("Creating plot...") plot = sns.distplot(df[column], kde=params.get('kde')) fig = plot.get_figure() # bbox_inches is required to ensure that labels are cut off fig.savefig('plot.png', bbox_inches="tight") with open('plot.png', 'rb') as f: plot = base64.b64encode(f.read()) return { "csv": params.get('csv_data'), "plot": plot.decode('utf-8') }
Example #13
Source File: plot_trace.py From assaytools with GNU Lesser General Public License v2.1 | 5 votes |
def entry_point(): import sys #This allows us to import local inputs.py sys.path.append('./') import argparse # Define argparse stuff parser = argparse.ArgumentParser(description="""Plot the trace from the pickled object written by quickmodel """) parser.add_argument("--input", help="The pickle object you'd like to plot",required=True) parser.add_argument("--name", help="Name and extension of file that will be saved",required=True) args = parser.parse_args() # Define inputs # If an inputs###.py is defined, it is run and used. An inputs.json is also created. inputs_file = args.input filename = args.name db = pymc.database.pickle.load(inputs_file) ntraces = len(db.trace_names[0]) sns.set_style('white') sns.set_palette('muted', 12) fig = plt.figure(figsize=(6, 4 * ntraces)) for i, trace_name in enumerate(db.trace_names[0]): plt.subplot(ntraces, 1, i + 1) plt.plot(range(len(db.trace(trace_name)[:])), db.trace(trace_name)[:]) plt.title(trace_name) fig.savefig(filename, dpi=500, bbox_inches='tight')
Example #14
Source File: __init__.py From FRETBursts with GNU General Public License v2.0 | 4 votes |
def init_notebook(fs=13, seaborn_style='darkgrid', mpl_backend='inline', configure_logger=True, apionly=False): """ Set the default plot style for inline plots using the seaborn library. This function must be called from an ipython notebook or ipython QT console. Arguments: fs (int): base font size for text labels Returns: The imported seaborn library. By saving the return value you don't need to import seaborn again. """ if configure_logger: import logging logger = logging.getLogger('fretbursts') formatter = logging.Formatter('%(levelname)s %(name)s\n%(message)s') handler = logging.StreamHandler() handler.setFormatter(formatter) logger.addHandler(handler) if mpl_backend is not None: ip = get_ipython() ip.enable_matplotlib(mpl_backend) import seaborn as sns if not apionly: rc={'font.size': fs, 'axes.labelsize': fs, 'legend.fontsize': fs, 'axes.titlesize': fs*1.1, 'xtick.labelsize': fs, 'ytick.labelsize': fs, 'font.sans-serif': ['Arial', 'Liberation Sans'], } sns.set(rc=rc) blue = '#0055d4' green = '#2ca02c' color_brewer = sns.color_palette("Set1", 9) colors = np.array(color_brewer)[(1,0,2,3,4,8,6,7), :] colors = list(colors) colors[:3] = (blue, colors[1], green) sns.set_palette(colors, 8) sns.colors = colors sns.set_style(seaborn_style) return sns
Example #15
Source File: action.py From insightconnect-plugins with MIT License | 4 votes |
def run(self, params={}): # Set styles sns.set_palette(params.get('color_palette')) sns.set(style=params.get('margin_style')) # Process the data and create the plot try: decoded_data = base64.b64decode(params.get('csv_data')) except Exception as e: error = f"Failed to decode base64 encoded CSV data with error: {e}" self.logger.error(error) raise e df = pd.read_csv(BytesIO(decoded_data)) x = params.get('x_value') y = params.get('y_value') kind = params.get('kind') args = { "data": df, "x": x, "y": y, "kind": kind } if not x or (x not in df): error = f"Column for X value({x}) not in data set, cannot create plot..." self.logger.error(error) return Exception(error) elif not y or (y not in df): error = f"Column for Y value ({y}) not in data set, cannot create plot..." self.logger.error(error) return Exception(error) # JointPlots have the savefig method, call it directly self.logger.info("Creating plot...") plot = sns.jointplot(**args) # bbox_inches is required to ensure that labels are cut off plot.savefig('plot.png', bbox_inches='tight') with open('plot.png', 'rb', )as f: plot = base64.b64encode(f.read()) return { "csv": params.get('csv_data'), "plot": plot.decode('utf-8') }
Example #16
Source File: graph.py From pipedream with MIT License | 4 votes |
def plot_bar_graph(self, all_values, ylabel, legend, output_template, output_directory): import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as plt from matplotlib.backends.backend_pdf import PdfPages import seaborn as sns matplotlib.rc('text', usetex=True) sns.set_style('ticks') sns.set_style({'font.family':'sans-serif'}) flatui = ['#002A5E', '#FD151B', '#8EBA42', '#348ABD', '#988ED5', '#777777', '#8EBA42', '#FFB5B8'] sns.set_palette(flatui) paper_rc = {'lines.linewidth': 2, 'lines.markersize': 10} sns.set_context("paper", font_scale=3, rc=paper_rc) current_palette = sns.color_palette() labels = ["Compute_times", "Activations", "Parameters"] ylabels = ["Compute time\n(milliseconds)", "Activation size\n(bytes)", "Parameter size\n(bytes)"] for i in range(3): plt.figure(figsize=(10, 4)) ax = plt.subplot2grid((1, 1), (0, 0), colspan=1) values_sum = sum([all_values[j][i] for j in range(len(all_values))]) # Truncate the number of values plotted, since bars become very thin otherwise. values = [all_values[j][i] for j in range(len(all_values))][:400] if legend: ax.bar(range(len(values)), values, label="Sum: %.1f" % values_sum) else: ax.bar(range(len(values)), values) ax.set_xlim([0, None]) ax.set_ylim([0, None]) ax.set_xlabel("Layer ID") if ylabel is not None: ax.set_ylabel(ylabel) else: ax.set_ylabel(ylabels[i]) if legend: plt.legend() with PdfPages(os.path.join(output_directory, (output_template % labels[i].lower()))) as pdf: pdf.savefig(bbox_inches='tight')
Example #17
Source File: prettyplot.py From uncertainpy with GNU General Public License v3.0 | 4 votes |
def set_style(style="seaborn-darkgrid", nr_colors=6, palette="hls", custom=True): """ Set the style of a plot Optional arguments style : str ["classic" | "dark_background" | "seaborn-pastel" | "seaborn" | "seaborn-deep" | "seaborn-colorblind" | "bmh" | "seaborn-white" | "seaborn-dark" | "seaborn-poster" | "seaborn-ticks" | "seaborn-bright" | "seaborn-whitegrid" | "seaborn-notebook" | "fivethirtyeight" | "seaborn-muted" | "grayscale" | "ggplot" | "seaborn-talk" | "seaborn-darkgrid" | "seaborn-dark-palette" | "seaborn-paper"] which matplotlib style to use as base. Default is "seaborn-darkgrid" nr_colors : int the number of colors in the seaborn color palette. Default is 6 palette : hls | husl | matplotlib colormap | seaborn color palette Set the matplotlib color cycle using a seaborn palette. Available seaborn palette names: deep | muted | bright | pastel | dark | colorblind Other options: hls | husl | any named matplotlib palette | list of colors Matplotlib pallettes can be specified as reversed palettes by appending "_r" to the name or as dark palettes by appending "_d" to the name. (These options are mutually exclusive, but the resulting list of colors can also be reversed). Default is "hsl" custom : bool If custom style should be used in addition to the standard style. Default is True """ plt.style.use(style) sns.set_palette(palette, n_colors=nr_colors) if custom: set_font() set_linestyle() set_tickstyle() set_legendstyle() set_figuresize() set_axestyle()
Example #18
Source File: plotting.py From fmridenoise with Apache License 2.0 | 4 votes |
def motion_plot(group_conf_summary): # Plot style setup plt.style.use('seaborn-white') plt.rcParams['font.family'] = 'Helvetica' colour = ["#fe6863", "#00a074"] palette = sns.set_palette(colour) small = 15 plt.rc('font', size=small) # controls default text sizes plt.rc('axes', titlesize=small) # fontsize of the axes title plt.rc('axes', linewidth=2.2) plt.rc('axes', labelsize=small) # fontsize of the x and y labels plt.rc('xtick', labelsize=small) # fontsize of the tick labels plt.rc('ytick', labelsize=small) # fontsize of the tick labels plt.rc('legend', fontsize=small) # legend fontsize plt.rc('lines', linewidth=2.2, color='gray') # ------------------------------------------ motion_dict = {'Mean FD': ['mean_fd', 0.2], 'Max FD': ['max_fd', 5], 'Percent of outlier dataframes (%)': ['perc_spikes', 20]} fig, axes = plt.subplots(1, 3, figsize=(16, 7)) fig.subplots_adjust(wspace=0.4, hspace=0.4) i = 0 for key, value in motion_dict.items(): plt.figure(figsize=(4, 6)) p = sns.swarmplot(y=value[0], x="task", hue="include", data=group_conf_summary, alpha=0.8, s=10, color=palette, ax=axes[i] ) p = sns.boxplot(y=value[0], x="task", data=group_conf_summary, showcaps=False, boxprops={'facecolor': 'None'}, showfliers=False, ax=axes[i]) p.title.set_text(f"Threshold = {value[1]}") p.axhline(value[1], ls='--', color="#fe6863") p.set(xlabel='') p.set(ylabel=key) p.get_legend().set_visible(False) p.tick_params(axis='both', which='both', length=6, width=2.2) i += 1 fig.suptitle(f"Excluding high motion subjects", va="top") return fig
Example #19
Source File: tearsheet.py From qstrader with MIT License | 4 votes |
def plot_results(self, filename=None): """ Plot the Tearsheet """ print('Plotting the tearsheet...') rc = { 'lines.linewidth': 1.0, 'axes.facecolor': '0.995', 'figure.facecolor': '0.97', 'font.family': 'serif', 'font.serif': 'Ubuntu', 'font.monospace': 'Ubuntu Mono', 'font.size': 10, 'axes.labelsize': 10, 'axes.labelweight': 'bold', 'axes.titlesize': 10, 'xtick.labelsize': 8, 'ytick.labelsize': 8, 'legend.fontsize': 10, 'figure.titlesize': 12 } sns.set_context(rc) sns.set_style("whitegrid") sns.set_palette("deep", desat=.6) vertical_sections = 5 fig = plt.figure(figsize=(16, 12)) fig.suptitle(self.title, y=0.94, weight='bold') gs = gridspec.GridSpec(vertical_sections, 3, wspace=0.25, hspace=0.5) stats = self.get_results(self.strategy_equity) bench_stats = None if self.benchmark_equity is not None: bench_stats = self.get_results(self.benchmark_equity) ax_equity = plt.subplot(gs[:2, :]) ax_drawdown = plt.subplot(gs[2, :]) ax_monthly_returns = plt.subplot(gs[3, :2]) ax_yearly_returns = plt.subplot(gs[3, 2]) ax_txt_curve = plt.subplot(gs[4, 0]) # ax_txt_trade = plt.subplot(gs[4, 1]) # ax_txt_time = plt.subplot(gs[4, 2]) self._plot_equity(stats, bench_stats=bench_stats, ax=ax_equity) self._plot_drawdown(stats, ax=ax_drawdown) self._plot_monthly_returns(stats, ax=ax_monthly_returns) self._plot_yearly_returns(stats, ax=ax_yearly_returns) self._plot_txt_curve(stats, bench_stats=bench_stats, ax=ax_txt_curve) # self._plot_txt_trade(stats, ax=ax_txt_trade) # self._plot_txt_time(stats, ax=ax_txt_time) # Plot the figure plt.show()
Example #20
Source File: action.py From insightconnect-plugins with MIT License | 4 votes |
def run(self, params={}): # Set styles sns.set_palette(params.get('color_palette')) sns.set(style=params.get('margin_style')) # Process the data and create the plot try: decoded_data = base64.b64decode(params.get('csv_data')) except Exception as e: error = f"Failed to decode base64 encoded CSV data with error: {e}" self.logger.error(error) raise e df = pd.read_csv(BytesIO(decoded_data)) x = params.get('x_value') y = params.get('y_value') hue = params.get('hue') args = { "data": df, "x": x, "y": y } if not x or (x not in df): error = f"Column ({x}) not in data set, cannot create plot..." self.logger.error(error) return Exception(error) elif not y or (y not in df): error = f"Column ({y}) not in data set, cannot create plot..." self.logger.error(error) return Exception(error) if hue and (len(hue) > 0): args['hue'] = hue if hue not in df: error = f"Column for hue ({hue}) not in data set, cannot create plot..." self.logger.error(error) return Exception(error) # AxesSubplots (the plot object returned) don't have the savefig method, get the figure, then save it self.logger.info("Creating plot...") plot = sns.lineplot(**args) fig = plot.get_figure() # bbox_inches is required to ensure that labels are cut off fig.savefig('plot.png', bbox_inches="tight") with open('plot.png', 'rb', )as f: plot = base64.b64encode(f.read()) return { "csv": params.get('csv_data'), "plot": plot.decode('utf-8') }
Example #21
Source File: five_number_plot.py From Deep-SVDD with MIT License | 4 votes |
def plot_five_number_summary(data, title, ylabel="Values", xlabel="Epochs", export_pdf=False, show=False): n_series = len(data) sns.set_style("white") sns.set_palette("colorblind", n_series) y_maxs = np.zeros(n_series) y_mins = np.zeros(n_series) epoch_maxs = np.zeros(n_series) i = 0 for key in data: epochs = data[key].shape[1] x = np.arange(0, epochs) max = np.max(data[key], axis=0) upper_quant = np.percentile(data[key], 95, axis=0) median = np.median(data[key], axis=0) lower_quant = np.percentile(data[key], 5, axis=0) min = np.min(data[key], axis=0) plt.plot(x, median, '-', color=sns.color_palette()[i], label=key) plt.fill_between(x, lower_quant, upper_quant, alpha=0.25, facecolor=sns.color_palette()[i]) plt.fill_between(x, min, max, alpha=0.25, facecolor=sns.color_palette()[i]) y_maxs[i] = np.max(data[key]) y_mins[i] = np.min(data[key]) epoch_maxs[i] = epochs i += 1 spread = np.max(y_maxs) - np.min(y_mins) plt.ylim(np.min(y_mins) - 0.025 * spread, np.max(y_maxs) + 0.025 * spread) plt.yscale('symlog') plt.xlim(0, np.max(epoch_maxs)-1) plt.grid(True, which="both") plt.title(title) plt.xlabel(xlabel) plt.ylabel(ylabel) plt.legend() if export_pdf: plt.savefig(export_pdf, bbox_inches='tight', pad_inches=0.1) plt.clf() if show: plt.show()
Example #22
Source File: plot.py From pyexperiment with MIT License | 4 votes |
def setup_plotting(options=None, override_setup=True): """Setup basic style for matplotlib figures """ if options is None: options = {} def option_or_conf(key, default): """Get a value from a dictionary, the configuration or a default value """ prefix = 'pyexperiment.plot' if key in options: return options[key] elif prefix + conf.SECTION_SEPARATOR + key in conf: return conf[prefix + conf.SECTION_SEPARATOR + key] else: return default # Import seaborn if required sns = None if option_or_conf('seaborn.enable', True): try: import seaborn as sns except ImportError: log.warning("Cannot import seaborn. Proceeding without.") # Global should be ok here global _SETUP_DONE # pylint: disable=global-statement if not override_setup and _SETUP_DONE: return False font_size = int(option_or_conf('font_size', 14)) font = {'family': 'normal', 'weight': 'normal', 'size': font_size} matplotlib.rc('font', **font) matplotlib.rc('text', usetex=bool(option_or_conf('use_tex', True))) matplotlib.rc('lines', linewidth=int(option_or_conf('line_width', 4))) matplotlib.rc('figure', facecolor='white') label_size = int(option_or_conf('label_size', 14)) matplotlib.rc('xtick', labelsize=label_size) matplotlib.rc('ytick', labelsize=label_size) if sns is not None: sns.set_style(option_or_conf('seaborn.style', 'darkgrid')) sns.set_palette(option_or_conf('seaborn.palette_name', 'colorblind'), desat=option_or_conf('seaborn.desat', 0.6)) _SETUP_DONE = True return True
Example #23
Source File: tearsheet.py From qstrader with MIT License | 4 votes |
def plot_results(self, filename=None): """ Plot the Tearsheet """ rc = { 'lines.linewidth': 1.0, 'axes.facecolor': '0.995', 'figure.facecolor': '0.97', 'font.family': 'serif', 'font.serif': 'Ubuntu', 'font.monospace': 'Ubuntu Mono', 'font.size': 10, 'axes.labelsize': 10, 'axes.labelweight': 'bold', 'axes.titlesize': 10, 'xtick.labelsize': 8, 'ytick.labelsize': 8, 'legend.fontsize': 10, 'figure.titlesize': 12 } sns.set_context(rc) sns.set_style("whitegrid") sns.set_palette("deep", desat=.6) if self.rolling_sharpe: offset_index = 1 else: offset_index = 0 vertical_sections = 5 + offset_index fig = plt.figure(figsize=(10, vertical_sections * 3.5)) fig.suptitle(self.title, y=0.94, weight='bold') gs = gridspec.GridSpec(vertical_sections, 3, wspace=0.25, hspace=0.5) stats = self.get_results() ax_equity = plt.subplot(gs[:2, :]) if self.rolling_sharpe: ax_sharpe = plt.subplot(gs[2, :]) ax_drawdown = plt.subplot(gs[2 + offset_index, :]) ax_monthly_returns = plt.subplot(gs[3 + offset_index, :2]) ax_yearly_returns = plt.subplot(gs[3 + offset_index, 2]) ax_txt_curve = plt.subplot(gs[4 + offset_index, 0]) ax_txt_trade = plt.subplot(gs[4 + offset_index, 1]) ax_txt_time = plt.subplot(gs[4 + offset_index, 2]) self._plot_equity(stats, ax=ax_equity) if self.rolling_sharpe: self._plot_rolling_sharpe(stats, ax=ax_sharpe) self._plot_drawdown(stats, ax=ax_drawdown) self._plot_monthly_returns(stats, ax=ax_monthly_returns) self._plot_yearly_returns(stats, ax=ax_yearly_returns) self._plot_txt_curve(stats, ax=ax_txt_curve) self._plot_txt_trade(stats, ax=ax_txt_trade) self._plot_txt_time(stats, ax=ax_txt_time) # Plot the figure plt.show(block=False) if filename is not None: fig.savefig(filename, dpi=150, bbox_inches='tight')
Example #24
Source File: action.py From insightconnect-plugins with MIT License | 4 votes |
def run(self, params={}): # Set styles sns.set_palette(params.get('color_palette')) sns.set(style=params.get('margin_style')) # Process the data and create the plot try: decoded_data = base64.b64decode(params.get('csv_data')) except Exception as e: error = f"Failed to decode base64 encoded CSV data with error: {e}" self.logger.error(error) raise e df = pd.read_csv(BytesIO(decoded_data)) kind = params.get('kind') hue = params.get('hue') args = { "kind": kind } if hue and (len(hue) > 0): args['hue'] = hue if hue not in df: error = f"Column for hue ({hue}) not in data set, cannot create plot..." self.logger.error(error) return Exception(error) # Pairgrids have the savefig method, call it directly self.logger.info("Creating plot...") plot = sns.pairplot(df, **args) # bbox_inches is required to ensure that labels are cut off plot.savefig('plot.png', bbox_inches="tight") with open('plot.png', 'rb') as f: plot = base64.b64encode(f.read()) return { "csv": params.get('csv_data'), "plot": plot.decode('utf-8') }
Example #25
Source File: action.py From insightconnect-plugins with MIT License | 4 votes |
def run(self, params={}): # Set styles sns.set_palette(params.get('color_palette')) sns.set(style=params.get('margin_style')) # Process the data and create the plot try: decoded_data = base64.b64decode(params.get('csv_data')) except Exception as e: error = f"Failed to decode base64 encoded CSV data with error: {e}" self.logger.error(error) raise e df = pd.read_csv(BytesIO(decoded_data)) x = params.get('x_value') y = params.get('y_value') hue = params.get('hue') args = { "data": df, "x": x, "y": y } if not x or (x not in df): error = f"Column ({x}) not in data set, cannot create plot..." self.logger.error(error) return Exception(error) elif not y or (y not in df): error = f"Column ({y}) not in data set, cannot create plot..." self.logger.error(error) return Exception(error) if hue and (len(hue) > 0): args['hue'] = hue if hue not in df: error = f"Column for hue ({hue}) not in data set, cannot create plot..." self.logger.error(error) return Exception(error) # AxesSubplots (the plot object returned) don't have the savefig method, get the figure, then save it self.logger.info("Creating plot...") plot = sns.scatterplot(**args) fig = plot.get_figure() # bbox_inches is required to ensure that labels are cut off fig.savefig('plot.png', bbox_inches="tight") with open('plot.png', 'rb', )as f: plot = base64.b64encode(f.read()) return { "csv": params.get('csv_data'), "plot": plot.decode('utf-8') }
Example #26
Source File: benchmarks.py From datawig with Apache License 2.0 | 4 votes |
def plot_results(results): import matplotlib.pyplot as plt import seaborn as sns df = pd.read_csv(open(os.path.join(dir_path, 'benchmark_results.csv')) df['mse_percent'] = df.mse / df.groupby(['data','missingness','percent_missing'])['mse'].transform(max) df.groupby(['missingness','percent_missing','imputer']).agg({'mse_percent':'median'}) sns.set_style("whitegrid") sns.set_palette(sns.color_palette("RdBu_r", 7)) sns.set_context("notebook", font_scale=1.3, rc={"lines.linewidth": 1.5}) plt.figure(figsize=(12,3)) plt.subplot(1,3,1) sns.boxplot(hue='imputer', y='mse_percent', x='percent_missing', data=df[df['missingness']=='MCAR']) plt.title("Missing completely at random") plt.xlabel('Percent Missing') plt.ylabel("Relative MSE") plt.gca().get_legend().remove() plt.subplot(1,3,2) sns.boxplot(hue='imputer', y='mse_percent', x='percent_missing', data=df[df['missingness']=='MAR']) plt.title("Missing at random") plt.ylabel('') plt.xlabel('Percent Missing') plt.gca().get_legend().remove() plt.subplot(1,3,3) sns.boxplot(hue='imputer', y='mse_percent', x='percent_missing', data=df[df['missingness']=='MNAR']) plt.title("Missing not at random") plt.ylabel("") plt.xlabel('Percent Missing') handles, labels = plt.gca().get_legend_handles_labels() l = plt.legend(handles, labels, bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) plt.tight_layout() plt.savefig('benchmarks_datawig.pdf') experiment()