Seaborn set context

Seaborn set context DEFAULT

Python seaborn.set_context() Examples

The following are 30 code examples for showing how to use seaborn.set_context(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module seaborn, or try the search function .

Example 1

def _plot_weights(self, title, file, layer_index=0, vmin=-5, vmax=5): import seaborn as sns sns.set_context("paper") layers = self.iwp.estimator.steps[-1][1].coefs_ layer = layers[layer_index] f, ax = plt.subplots(figsize=(18, 12)) weights = pd.DataFrame(layer) weights.index = self.iwp.inputs sns.set(font_scale=1.1) # Draw a heatmap with the numeric values in each cell sns.heatmap( weights, annot=True, fmt=".1f", linewidths=.5, ax=ax, cmap="difference", center=0, vmin=vmin, vmax=vmax, # annot_kws={"size":14}, ) ax.tick_params(labelsize=18) f.tight_layout() f.savefig(file)

Example 2

def plot_avg_return(file_name, granularity): plotting_data = torch.load(file_name + "_processed_data") returns = plotting_data['returns'] unique_frames = plotting_data['unique_frames'] x_len = len(unique_frames) x_index = [i for i in numpy.arange(0, x_len, granularity)] x = unique_frames[::granularity] y = numpy.transpose(numpy.array(returns)[x_index, :]) f, ax = plt.subplots(1, 1, figsize=[3, 2], dpi=300) sns.set_style("ticks") sns.set_context("paper") # Find the order of magnitude of the last frame order = int(math.log10(unique_frames[-1])) range_frames = int(unique_frames[-1]/ (10**order)) sns.tsplot(data=y, time=numpy.array(x)/(10**order), color='b') ax.set_xticks(numpy.arange(range_frames + 1)) plt.show() f.savefig(file_name + "_avg_return.pdf", bbox_inches="tight") plt.close(f)

Example 3

def plot_evaluation_episode_reward(): pylab.clf() sns.set_context("poster") pylab.plot(0, 0) episodes = [0] average_scores = [0] median_scores = [0] for n in xrange(len(csv_evaluation)): params = csv_evaluation[n] episodes.append(params[0]) average_scores.append(params[1]) median_scores.append(params[2]) pylab.plot(episodes, average_scores, sns.xkcd_rgb["windows blue"], lw=2) pylab.xlabel("episodes") pylab.ylabel("average score") pylab.savefig("%s/evaluation_episode_average_reward.png" % args.plot_dir) pylab.clf() pylab.plot(0, 0) pylab.plot(episodes, median_scores, sns.xkcd_rgb["windows blue"], lw=2) pylab.xlabel("episodes") pylab.ylabel("median score") pylab.savefig("%s/evaluation_episode_median_reward.png" % args.plot_dir)

Example 4

def plot_kim_curve(tmp): sns.set_context("notebook", font_scale=1.5, rc={"lines.linewidth": 5}) sns.set_style("darkgrid") plt.figure(figsize=(20, 10)) plt.hold('on') plt.plot(np.linspace(0, 0.3, 100), tmp['kc_avg']) plt.ylim([0, 1]) # plt.figure(figsize=(10,5)) # plt.hold('on') # legend = [] # for k,v in bench_res.iteritems(): # plt.plot(np.linspace(0, 0.3, 100), v['kc_avg']) # legend.append(k) # plt.ylim([0, 1]) # plt.legend(legend, loc='lower right')

Example 5

def learning_curve(self, idxs=[2,3,5,6]): import seaborn as sns import matplotlib.pyplot as plt plt.switch_backend('agg') # set style sns.set_context("paper", font_scale=1.5,) # sns.set_style("ticks", { # "font.family": "Times New Roman", # "font.serif": ["Times", "Palatino", "serif"]}) for idx in idxs: plt.plot(self.logs[self.args.trigger], self.logs[self.header[idx]], label=self.header[idx]) plt.ylabel(" {} / {} ".format(repr(self.criterion), repr(self.evaluator))) if self.args.trigger == 'epoch': plt.xlabel("Epochs") else: plt.xlabel("Iterations") plt.suptitle("Training log of {}".format(self.method)) # remove top&left line # sns.despine() plt.legend(bbox_to_anchor=(1.01, 1), loc=2, borderaxespad=0.) plt.savefig(os.path.join(Logs_DIR, 'curve', '{}.png'.format(self.repr)), format='png', bbox_inches='tight', dpi=144)

Example 6

def __init__(self): sns.set_style("ticks") sns.set_context("paper", font_scale=1.5) # color palette from colorbrewer (up to 4 colors, good for print and black&white printing) # color_brewer_palette = ['#e66101', '#5e3c99', '#fdb863', '#b2abd2'] # most journals: 300dpi plt.rcParams["savefig.dpi"] = 300 # most journals: 9 cm (or 3.5 inch) for single column width and 18.5 cm (or 7.3 inch) for double column width. plt.rcParams["figure.autolayout"] = False plt.rcParams["figure.figsize"] = 7.3, 4 plt.rcParams["axes.labelsize"] = 16 plt.rcParams["axes.titlesize"] = 16 plt.rcParams["xtick.labelsize"] = 16 plt.rcParams["ytick.labelsize"] = 16 plt.rcParams["font.size"] = 32 plt.rcParams["lines.linewidth"] = 2.0 plt.rcParams["lines.markersize"] = 8 plt.rcParams["legend.fontsize"] = 14

Example 7

def plotSleepValueHeatmap(intradayStats, sleepValue=1): sns.set_context("poster") sns.set_style("darkgrid") xTicksDiv = 20 #stepSize = int(len(xticks)/xTicksDiv) stepSize = 60 xticks = [x for x in intradayStats.columns.values] keptticks = xticks[::stepSize] xticks = ['' for _ in xticks] xticks[::stepSize] = keptticks plt.figure(figsize=(16, 4.2)) g = sns.heatmap(intradayStats.loc[sleepValue].reshape(1,-1)) g.set_xticklabels(xticks, rotation=45) g.set_yticklabels([]) g.set_ylabel(sleepStats.SLEEP_VALUES[sleepValue]) plt.tight_layout() sns.plt.show()

Example 8

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 9

def make_slashdot_figures(output_path_prefix, method_name_list, slashdot_mse, slashdot_jaccard, slashdot_k_list): sns.set_style("darkgrid") sns.set_context("paper") translator = get_method_name_to_legend_name_dict() slashdot_k_list = list(slashdot_k_list) fig, axes = plt.subplots(1, 2, sharex=True) axes[0].set_title("SlashDot Comments") axes[1].set_title("SlashDot Users") plt.locator_params(nbins=8) # Comments for m, method in enumerate(method_name_list): axes[0].set_ylabel("MSE") axes[0].set_xlabel("Lifetime (sec)") axes[0].plot(slashdot_k_list[1:], handle_nan(slashdot_mse[method]["comments"].mean(axis=1))[1:], label=translator[method]) # Users for m, method in enumerate(method_name_list): # axes[1].set_ylabel("MSE") axes[1].set_xlabel("Lifetime (sec)") axes[1].plot(slashdot_k_list[1:], handle_nan(slashdot_mse[method]["users"].mean(axis=1))[1:], label=translator[method]) axes[1].legend(loc="upper right") # plt.show() plt.savefig(output_path_prefix + "_mse_slashdot_SNOW" + ".png", format="png") plt.savefig(output_path_prefix + "_mse_slashdot_SNOW" + ".eps", format="eps")

Example 10

def make_barrapunto_figures(output_path_prefix, method_name_list, barrapunto_mse, barrapunto_jaccard, barrapunto_k_list): sns.set_style("darkgrid") sns.set_context("paper") translator = get_method_name_to_legend_name_dict() barrapunto_k_list = list(barrapunto_k_list) fig, axes = plt.subplots(1, 2, sharex=True) axes[0].set_title("BarraPunto Comments") axes[1].set_title("BarraPunto Users") plt.locator_params(nbins=8) # Comments for m, method in enumerate(method_name_list): axes[0].set_ylabel("MSE") axes[0].set_xlabel("Lifetime (sec)") axes[0].plot(barrapunto_k_list[1:], handle_nan(barrapunto_mse[method]["comments"].mean(axis=1))[1:], label=translator[method]) # Users for m, method in enumerate(method_name_list): # axes[1].set_ylabel("MSE") axes[1].set_xlabel("Lifetime (sec)") axes[1].plot(barrapunto_k_list[1:], handle_nan(barrapunto_mse[method]["users"].mean(axis=1))[1:], label=translator[method]) axes[1].legend(loc="upper right") # plt.show() plt.savefig(output_path_prefix + "_mse_barrapunto_SNOW" + ".png", format="png") plt.savefig(output_path_prefix + "_mse_barrapunto_SNOW" + ".eps", format="eps")

Example 11

def set_context(context="talk"): sns.set_context(context)

Example 12

def plot_gp(): np.random.seed(12345) sns.set_context("paper", font_scale=0.65) X_test = np.linspace(-10, 10, 100) X_train = np.array([-3, 0, 7, 1, -9]) y_train = np.sin(X_train) fig, axes = plt.subplots(2, 2) alphas = [0, 1e-10, 1e-5, 1] for ix, (ax, alpha) in enumerate(zip(axes.flatten(), alphas)): G = GPRegression(kernel="RBFKernel", alpha=alpha) G.fit(X_train, y_train) y_pred, conf = G.predict(X_test) ax.plot(X_train, y_train, "rx", label="observed") ax.plot(X_test, np.sin(X_test), label="true fn") ax.plot(X_test, y_pred, "--", label="MAP (alpha={})".format(alpha)) ax.fill_between(X_test, y_pred + conf, y_pred - conf, alpha=0.1) ax.set_xticks([]) ax.set_yticks([]) sns.despine() ax.legend() plt.tight_layout() plt.savefig("img/gp_alpha.png", dpi=300) plt.close("all")

Example 13

def plot_results(res, path): """Some results plots""" if res is None or len(res) == 0: return counts = base.pivot_count_data(res, idxcols=['name','ref']) x = base.get_fractions_mapped(res) print (x) import seaborn as sns sns.set_style('white') sns.set_context("paper",font_scale=1.2) fig = plotting.plot_fractions(x) fig.savefig(os.path.join(path,'libraries_mapped.png')) fig = plotting.plot_sample_counts(counts) fig.savefig(os.path.join(path,'total_per_sample.png')) fig = plotting.plot_read_count_dists(counts) fig.savefig(os.path.join(path,'top_mapped.png')) scols,ncols = base.get_column_names(counts) for l,df in counts.groupby('ref'): if 'mirbase' in l: fig = plotting.plot_read_count_dists(df) fig.savefig(os.path.join(path,'top_%s.png' %l)) #if len(scols)>1: # fig = plotting.expression_clustermap(counts) # fig.savefig(os.path.join(path,'expr_map.png')) return

Example 14

def plot_episode_reward(): pylab.clf() sns.set_context("poster") pylab.plot(0, 0) episodes = [0] scores = [0] for n in xrange(len(csv_episode)): params = csv_episode[n] episodes.append(params[0]) scores.append(params[1]) pylab.plot(episodes, scores, sns.xkcd_rgb["windows blue"], lw=2) pylab.xlabel("episodes") pylab.ylabel("score") pylab.savefig("%s/episode_reward.png" % args.plot_dir)

Example 15

def plot_training_episode_highscore(): pylab.clf() sns.set_context("poster") pylab.plot(0, 0) episodes = [0] highscore = [0] for n in xrange(len(csv_training_highscore)): params = csv_training_highscore[n] episodes.append(params[0]) highscore.append(params[1]) pylab.plot(episodes, highscore, sns.xkcd_rgb["windows blue"], lw=2) pylab.xlabel("episodes") pylab.ylabel("highscore") pylab.savefig("%s/training_episode_highscore.png" % args.plot_dir)

Example 16

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 17

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 18

def generate_clusters(words, vectors_in_2D, print_status=True): # HDBSCAN, i.e. hierarchical density-based spatial clustering of applications with noise (https://github.com/lmcinnes/hdbscan) vectors = vectors_in_2D sns.set_context('poster') sns.set_color_codes() plot_kwds = {'alpha' : 0.5, 's' : 500, 'linewidths': 0} clusters = HDBSCAN(min_cluster_size=2).fit_predict(vectors) palette = sns.color_palette("husl", np.unique(clusters).max() + 1) colors = [palette[cluster_index] if cluster_index >= 0 else (0.0, 0.0, 0.0) for cluster_index in clusters] fig = plt.figure(figsize=(30, 30)) plt.scatter(vectors.T[0], vectors.T[1], c=colors, **plot_kwds) plt.axis('off') x_vals = [i[0] for i in vectors] y_vals = [i[1] for i in vectors] plt.ylim(min(y_vals)-0.3, max(y_vals)+0.3) plt.xlim(min(x_vals)-0.3, max(x_vals)+0.3) font_path = getcwd() + '/fonts/Comfortaa-Regular.ttf' font_property = matplotlib.font_manager.FontProperties(fname=font_path, size=24) for i, word in enumerate(words): if type(word) != type(None): if type(word) != type(""): word = unidecode(word).replace("_", " ") else: word = word.replace("_", " ") text_object = plt.annotate(word, xy=(x_vals[i], y_vals[i]+0.05), font_properties=font_property, color=colors[i], ha="center") plt.subplots_adjust(left=(500/3000), right=(2900/3000), top=1.0, bottom=(300/2700)) plt.savefig(get_visualization_file_path(print_status), bbox_inches="tight") return clusters

Example 19

def savePair(df,samplesize=20000): df1 = df.sample(samplesize) sns.set(style="ticks") sns.set_context("paper") sns.pairplot(df1) plt.title('Pair Graph') plt.savefig(pair_path) #画滑动平均图,默认12阶

Example 20

def heatmap(dfr, outfilename=None, title=None, params=None): """Return seaborn heatmap with cluster dendrograms. :param dfr: pandas DataFrame with relevant data :param outfilename: path to output file (indicates output format) :param title: :param params: """ # Decide on figure layout size: a minimum size is required for # aesthetics, and a maximum to avoid core dumps on rendering. # If we hit the maximum size, we should modify font size. maxfigsize = 120 calcfigsize = dfr.shape[0] * 1.1 figsize = min(max(8, calcfigsize), maxfigsize) if figsize == maxfigsize: scale = maxfigsize / calcfigsize sns.set_context("notebook", font_scale=scale) # Add a colorbar? if params.classes is None: col_cb = None else: col_cb = get_colorbar(dfr, params.classes) # Add attributes to parameter object, and draw heatmap params.colorbar = col_cb params.figsize = figsize params.linewidths = 0.25 fig = get_clustermap(dfr, params, title=title) # Save to file if outfilename: fig.savefig(outfilename) # Return clustermap return fig

Example 21

def learning_curve(self, idxs=[2,3,5,6]): import seaborn as sns import matplotlib.pyplot as plt plt.switch_backend('agg') # set style sns.set_context("paper", font_scale=1.5,) # sns.set_style("ticks", { # "font.family": "Times New Roman", # "font.serif": ["Times", "Palatino", "serif"]}) for idx in idxs: plt.plot(self.logs[self.args.trigger], self.logs[self.header[idx]], label=self.header[idx]) plt.ylabel(" {} / {} ".format(repr(self.criterion), repr(self.evaluator))) if self.args.trigger == 'epoch': plt.xlabel("Epochs") else: plt.xlabel("Iterations") plt.suptitle("Training log of {}".format(self.method)) # remove top&left line # sns.despine() plt.legend(bbox_to_anchor=(1.01, 1), loc=2, borderaxespad=0.) plt.savefig(os.path.join(Logs_DIR, 'curve', '{}.png'.format(self.repr)), format='png', bbox_inches='tight', dpi=144) # plt.savefig(os.path.join(Logs_DIR, 'curve', '{}.eps'.format(self.repr)), # format='eps', bbox_inches='tight', dpi=300) return 0

Example 22

def init_plot_set(): """全局plot设置""" import seaborn as sns sns.set_context('notebook', rc={'figure.figsize': g_plt_figsize}) sns.set_style("darkgrid") import matplotlib # conda 5.0后需要添加单独matplotlib的figure设置否则pandas的plot size不生效 matplotlib.rcParams['figure.figsize'] = g_plt_figsize

Example 23

def sample_711(): """ 7.1.1 趋势跟踪和均值回复的周期重叠性 :return: """ sns.set_context(rc={'figure.figsize': (14, 7)}) sns.regplot(x=np.arange(0, kl_pd.shape[0]), y=kl_pd.close.values, marker='+') plt.show() from abupy import ABuRegUtil deg = ABuRegUtil.calc_regress_deg(kl_pd.close.values) plt.show() print('趋势角度:' + str(deg)) start = 0 # 前1/4的数据 end = int(kl_pd.shape[0] / 4) # 将x也使用arange切割 x = np.arange(start, end) # y根据start,end进行切片 y = kl_pd.close.values[start:end] sns.regplot(x=x, y=y, marker='+') plt.show() start = int(kl_pd.shape[0] / 4) # 向前推1/4单位个时间 end = start + int(kl_pd.shape[0] / 4) sns.regplot(x=np.arange(start, end), y=kl_pd.close.values[start:end], marker='+') plt.show()

Example 24

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 25

def _set_sns_context(n_kernel): import seaborn as sns if n_kernel <= 25: sns.set_context("notebook", rc={"ytick.labelsize":26}) elif 25 < n_kernel <= 50: sns.set_context("notebook", rc={"ytick.labelsize":22}) elif 50 < n_kernel <= 75: sns.set_context("notebook", rc={"ytick.labelsize":14}) elif 75 < n_kernel <= 100: sns.set_context("notebook", rc={"ytick.labelsize":8}) else: sns.set_context("notebook", rc={"ytick.labelsize":5})

Example 26

def set_chart_context(context): sns.set_context(context)

Example 27

def plot_rewards(self, rwd_greedy): """ Plot the cumulative reward per episode as a function of episode number. Notes ----- Saves plot to the file ``./img/<agent>-<env>.png`` Parameters ---------- rwd_greedy : float The cumulative reward earned with a final execution of a greedy target policy. """ try: import matplotlib.pyplot as plt import seaborn as sns # https://seaborn.pydata.org/generated/seaborn.set_context.html # https://seaborn.pydata.org/generated/seaborn.set_style.html sns.set_style("white") sns.set_context("notebook", font_scale=1) except: fstr = "Error importing `matplotlib` and `seaborn` -- plotting functionality is disabled" raise ImportError(fstr) R = self.rewards fig, ax = plt.subplots() x = np.arange(len(R["total"])) y = R["smooth_total"] y_raw = R["total"] ax.plot(x, y, label="smoothed") ax.plot(x, y_raw, alpha=0.5, label="raw") ax.axhline(y=rwd_greedy, xmin=min(x), xmax=max(x), ls=":", label="final greedy") ax.legend() sns.despine() env = self.agent.env_info["id"] agent = self.agent.hyperparameters["agent"] ax.set_xlabel("Episode") ax.set_ylabel("Cumulative reward") ax.set_title("{} on '{}'".format(agent, env)) plt.savefig("img/{}-{}.png".format(agent, env)) plt.close("all")

Example 28

def plot_gp_dist(): np.random.seed(12345) sns.set_context("paper", font_scale=0.95) X_test = np.linspace(-10, 10, 100) X_train = np.array([-3, 0, 7, 1, -9]) y_train = np.sin(X_train) fig, axes = plt.subplots(1, 3) G = GPRegression(kernel="RBFKernel", alpha=0) G.fit(X_train, y_train) y_pred_prior = G.sample(X_test, 3, "prior") y_pred_posterior = G.sample(X_test, 3, "posterior_predictive") for prior_sample in y_pred_prior: axes[0].plot(X_test, prior_sample.ravel(), lw=1) axes[0].set_title("Prior samples") axes[0].set_xticks([]) axes[0].set_yticks([]) for post_sample in y_pred_posterior: axes[1].plot(X_test, post_sample.ravel(), lw=1) axes[1].plot(X_train, y_train, "ko", ms=1.2) axes[1].set_title("Posterior samples") axes[1].set_xticks([]) axes[1].set_yticks([]) y_pred, conf = G.predict(X_test) axes[2].plot(X_test, np.sin(X_test), lw=1, label="true function") axes[2].plot(X_test, y_pred, lw=1, label="MAP estimate") axes[2].fill_between(X_test, y_pred + conf, y_pred - conf, alpha=0.1) axes[2].plot(X_train, y_train, "ko", ms=1.2, label="observed") axes[2].legend(fontsize="x-small") axes[2].set_title("Posterior mean") axes[2].set_xticks([]) axes[2].set_yticks([]) fig.set_size_inches(6, 2) plt.tight_layout() plt.savefig("img/gp_dist.png", dpi=300) plt.close("all")

Example 29

def plot_restraint_and_barostat_analysis(): """Plot the Figure showing info for the restraint and barostat analysis.""" import seaborn as sns from matplotlib import pyplot as plt sns.set_style('whitegrid') sns.set_context('paper', font_scale=1.0) # Create two columns, each of them share the x-axis. fig = plt.figure(figsize=(7.25, 4)) # Restraint distribution axes. ax1 = fig.add_subplot(221) ax2 = fig.add_subplot(223, sharex=ax1) barostat_axes = [ax1, ax2] # Volume distribution axes. ax3 = fig.add_subplot(222) ax4 = fig.add_subplot(224, sharex=ax3) restraint_axes = [ax3, ax4] # Plot barostat analysis. plot_volume_distributions(barostat_axes, plot_predicted=True) # Plot restraint analysis. system_id = 'OA-G3-0' plot_restraint_analysis(system_id, restraint_axes) # Configure axes. restraint_axes[0].set_xlim((0, 10.045)) restraint_axes[1].set_ylim((-7, -3.9)) for ax in restraint_axes + barostat_axes: ax.tick_params(axis='x', which='major', pad=0.1) ax.tick_params(axis='y', which='major', pad=0.1) plt.tight_layout(pad=0.3) # plt.show() output_file_path = os.path.join(SAMPLING_PAPER_DIR_PATH, 'Figure5-restraint_barostat', 'restraint_barostat.pdf') os.makedirs(os.path.dirname(output_file_path), exist_ok=True) plt.savefig(output_file_path) # ============================================================================= # FIGURE 6 - HREX INITIAL BIAS # =============================================================================

Example 30

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')
Sours: https://www.programcreek.com/python/example/96216/seaborn.set_context

Python set_context Examples

def plot_rolling_auto_home(df_attack=None,df_defence=None, window=5, nstd=1, detected_events_home=None, detected_events_away=None, sky_events=None): sns.set_context("notebook", font_scale=1.8 ,rc={"lines.linewidth": 3.5, "figure.figsize":(18,12) }) plt.subplots_adjust(bottom=0.85) mean = pd.rolling_mean(df_attack, center=True, window=window) std = pd.rolling_std(df_attack, center=True, window=window) detected_plot_extrema = df_attack.ix[argrelextrema(df_attack.values, np.greater)] df_filt_noise = df_attack[(df_attack > mean-std) & (df_attack < mean+std)] df_filt_noise = df_filt_noise.ix[detected_plot_extrema.index].dropna() df_filt_keep = df_attack[~((df_attack > mean-std) & (df_attack < mean+std))] df_filt_keep = df_filt_keep.ix[detected_plot_extrema.index].dropna() plt.plot(df_attack, color='#4CA64C', label='{} Attack'.format(all_matches[0]['home_team'].title())) plt.fill_between(df_attack.index, (mean-nstd*std), (mean+nstd*std), interpolate=False, alpha=0.4, color='#B2B2B2', label='$\mu + {} \\times \sigma$'.format(nstd)) plt.scatter(df_filt_keep.index, df_filt_keep.values, marker='*', s=120, color='#000000', zorder=10, label='Selected maxima post-filtering') plt.scatter(df_filt_noise.index, df_filt_noise.values, marker='x', s=120, color='#000000', zorder=10, label='Unselected maxima post-filtering') df_defence.apply(lambda x: -1*x).plot(color='#000000', label='{} Defence'.format(all_matches[0]['home_team'].title())) if(len(detected_events_home) > 0): classifier_events_df_home= pd.DataFrame(detected_events_home) classifier_events_df_home[classifier_events_df_home.category == 'GOAL'] if(len(detected_events_away) > 0): classifier_events_df_away= pd.DataFrame(detected_events_away) classifier_events_df_away[classifier_events_df_away.category == 'GOAL'] font0 = FontProperties(family='arial', weight='bold',style='italic', size=16) for i, row in classifier_events_df_home.iterrows(): if row.category == 'OTHER': continue plt.text(row.event, df_attack.max(), "{} {} {}".format(all_matches[0]['home_team'].upper(), row.category, row.event), rotation='vertical', color='black', bbox=dict(facecolor='green', alpha=0.2))#, transform=transform) for i, row in classifier_events_df_away.iterrows(): if row.category == 'OTHER': continue plt.text(row.event, (df_attack.max()), "{} {} {}".format(all_matches[0]['away_team'].upper(), row.category, row.event), rotation='vertical', color='black', bbox=dict(facecolor='red', alpha=0.2)) high_peak_position = 0; if(df_attack.max() > df_defence.max()): high_peak_position = -(df_defence.max() * 2.0) else: high_peak_position = -(df_defence.max() * 1.25) # Functionality to include Sky Sports text commentary updates on plot for goal events. # for i, row in pd.DataFrame(sky_events).iterrows(): # dedented_text = textwrap.dedent(row.text).strip() # plt.text(row.event, high_peak_position, "@SkySports {} AT {}:\n{}:\n{}".format(row.category, row.event.time(), row.title, textwrap.fill(dedented_text, width=40)), color='black', bbox=dict(facecolor='blue', alpha=0.2)) plt.legend(loc=4) ax = plt.gca() label = ax.set_xlabel('time') plt.ylabel('Tweet frequency') plt.title('{} vs. {} (WK {}) - rolling averages window={} mins'.format(all_matches[0]['home_team'].title(), all_matches[0]['away_team'].title(), all_matches[0]['dbname'], window)) plt.savefig('{}attack_{}_plain.pdf'.format(all_matches[0]['home_team'].upper(), all_matches[0]['away_team'].upper())) return detected_plot_extrema
Sours: https://python.hotexamples.com/examples/seaborn/-/set_context/python-set_context-function-examples.html
  1. Paducah kentucky apartments
  2. Abstract worship background
  3. Cts sport wagon review
  4. Online casino cheat engine

Global Settings¶

seaborn_image.set_context(mode='paper', fontfamily='sans-serif', fontweight='normal', rc=None

Set context for images with mode, fontfamily and fontweight. Additional, rc params can also be passed as dict

Parameters
  • mode (str, optional) – Plotting context mode. Depending on the context, axes width, fontsize, layout etc. are scaled. Options are ‘paper’, ‘notebook’, ‘presentation’, ‘talk’ and ‘poster’, by default “paper”.

  • fontfamily (str, optional) – Font-family to use, by default “sans-serif”.

  • fontweight (str, optional) – Font-weight to use. Options include ‘normal’ and ‘bold’, by default “bold”.

  • rc (dict, optional) – Additional matplotlib.rcParams to be passed to matplotlib, by default None.

Examples

>>> importseaborn_imageasisns>>> isns.set_context(mode="poster",fontfamily="sans-serif")>>> isns.set_context(rc={"axes.edgecolor":"red"})
seaborn_image.set_image(cmap='deep', origin='lower', interpolation='nearest', despine=False

Set deaults for plotting images

Parameters
  • cmap (str, optional) – Colormap to use accross images, by default to “deep”.

  • origin (str, optional) – Image origin - same as in matplotlib.pyplot.imshow, by default “lower”.

  • interpolation (str, optional) – Image interpolation - same as in matplotlib.pyplot.imshow, by default “nearest”.

  • despine (bool, optional) – Despine image and colorbar axes, by default False.

Examples

>>> importseaborn_imageasisns>>> isns.set_image(cmap="inferno",interpolation="bicubic")>>> isns.set_image(despine=False)
seaborn_image.set_scalebar(color='white', location='lowerright', width_fraction=0.025, height_fraction=None, length_fraction=0.3, scale_loc='top', box_alpha=0, rc=None

Set scalebar properties such as color, scale_loc, height_fraction, length_fraction, box_alpha, etc. To pass more properties that are not specified as key word argument, use the rc parameter. Refer to https://github.com/ppinard/matplotlib-scalebar for more information on additional parameters.

Parameters
  • color (str, optional) – Color of the scalebar, by default “white”.

  • location (str, optional) – Scalebar location on the image (same as matplotlib legend). by default “lower right”.

  • width_fraction (float, optional) – By default 0.025.

  • height_fraction (float, optional) – Deprecated - use width_fraction instead.

  • length_fraction (float, optional) – By default 0.3

  • scale_loc (str, optional) – Location of the scale number and units with respect to the bar, by default “top”.

  • box_alpha (float, optional) – Transparency of the box that contains the scalebar artist, by default 0.

  • rc (dict, optional) – Dictionary of scalebar properties to be set, by default None.

Examples

>>> importseaborn_imageasisns>>> isns.set_scalebar(color="red")>>> isns.set_scalebar(scale_loc="bottom")
seaborn_image.set_save_context(dpi=300

Set dpi for saving figures to disk

Parameters

dpi (int, optional) – Image dpi for saving, by default 300.

Examples

>>> importseaborn_imageasisns>>> isns.set_save_context(dpi=200)
seaborn_image.reset_defaults()¶

Reset rcParams to matplotlib defaults

Examples

>>> importseaborn_imageasisns>>> isns.reset_defaults()
Sours: https://seaborn-image.readthedocs.io/en/stable/api/_context.html
Lecture_45: Seaborn for Data Visualization -- Figure Aesthetics

Seaborn set_context() to adjust size of plot labels and lines

One of the challenges in making data visualization is making all aspects of a plot clearly visible. Often, you might see where the axis labels, tick labels are too small and not legible at all. Challenge is that the required sizes of plot aspects like labels, points, lines are not easy to set for different kind of media where the plot will be used. For example, plots used in a talk the label size should be different from the plots to be used in a poster.

Table of Contents

Adjust plot sizes in Seaborn

Seaborn’s set_context() function offers a great solution to solve the problem. With set_context(), one can specify the plotting context and adjust the size of labels and lines automatically.

Let us see examples of using Seaborn’s set_context() and adjust the sizes for a plot be used in a notebook, talk and poster.

Let us load the libraries needed.

import matplotlib.pyplot as plt import pandas as pd import seaborn as sns

We will use the Penguins data set to make the plot for different contexts.

penguins_data="https://raw.githubusercontent.com/datavizpyr/data/master/palmer_penguin_species.tsv"

Let us load the data directly from github page.

penguins_df = pd.read_csv(penguins_data, sep="\t") penguins_df.head()

Seaborn Scatterplot with default plot size

Let us make a scatterplot using Seaborn’s scatterplot function, but without setting a context for plot.

plt.figure(figsize=(10,8)) scatter_plot = sns.scatterplot(x="culmen_length_mm", y="flipper_length_mm", hue="species", style="sex", data=penguins_df) plt.xlabel("Culmen Length (mm)") plt.ylabel("Flipper Length (mm)") plt.savefig("Seaborn_scatterplot.png", format='png',dpi=150)

Seaborn set_context(): plot size suitable for notebook

Depending on the context of use, we might need to make the labels bigger. To make the plot for using in a notebook setting, we can use set_context() function with “notebook” as argument. In addition, we can also specify font_scale argument.

sns.set_context("notebook", font_scale=1.5)

The scatterplot made after setting the context will have the label size, lines and point size set for “notebook”.

plt.figure(figsize=(10,8)) sns.scatterplot(x="culmen_length_mm", y="flipper_length_mm", hue="species", style="sex", data=penguins_df) plt.xlabel("Culmen Length (mm)") plt.ylabel("Flipper Length (mm)") plt.title("Seaborn set_context: notebook") plt.savefig("set_context_notebook_Seaborn_scatterplot.png", format='png',dpi=150)
Seaborn Set Context: Notebook

Seaborn set plotting context for slides/talks

Similarly, if you want to use the data visualization in a slide/talk, we can use set_context() with “talk” argument.

sns.set_context("talk", font_scale=1.5)

We can see that sizes of labels, legends, data points are bigger than before.

Seaborn set_context: Talk

Seaborn set plotting context for poster

If you you are going to use the plot in a poster, where you might need the labels and other aspects of the plot really bigger to be legible, we can use set_context() with “poster” argument.

sns.set_context("poster", font_scale=1.1)

And we would get a plot suitable for using it in poster.

Seaborn set_context:  Poster

Filed Under: Python, Seaborn, Seaborn set_contextTagged With: Python, Seaborn

Sours: https://datavizpyr.com/seaborn-set_context-to-adjust-size-of-plot-labels-and-lines/

Context seaborn set

seaborn.set_context

Set the plotting context parameters.

This affects things like the size of the labels, lines, and other elements of the plot, but not the overall style. The base context is “notebook”, and the other contexts are “paper”, “talk”, and “poster”, which are version of the notebook parameters scaled by .8, 1.3, and 1.6, respectively.

Parameters:
context:dict, None, or one of {paper, notebook, talk, poster}

A dictionary of parameters or the name of a preconfigured set.

font_scale:float, optional

Separate scaling factor to independently scale the size of the font elements.

rc:dict, optional

Parameter mappings to override the values in the preset seaborn context dictionaries. This only updates parameters that are considered part of the context definition.

See also

return a dictionary of rc parameters, or use in a statement to temporarily set the context.
set the default parameters for figure style
set the default color palette for figures

Examples

>>> set_context("paper")
>>> set_context("talk",font_scale=1.4)
>>> set_context("talk",rc={"lines.linewidth":2})
Sours: http://man.hubwiz.com/docset/Seaborn.docset/Contents/Resources/Documents/generated/seaborn.set_context.html
Data Analysis with Python - Full Course for Beginners (Numpy, Pandas, Matplotlib, Seaborn)

.

Now discussing:

.



982 983 984 985 986