本文整理汇总了Python中seaborn.axes_style方法的典型用法代码示例。如果您正苦于以下问题:Python seaborn.axes_style方法的具体用法?Python seaborn.axes_style怎么用?Python seaborn.axes_style使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类seaborn
的用法示例。
在下文中一共展示了seaborn.axes_style方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: joint_plot
# 需要导入模块: import seaborn [as 别名]
# 或者: from seaborn import axes_style [as 别名]
def joint_plot(x, y, xlabel=None,
ylabel=None, xlim=None, ylim=None,
loc="best", color='#0485d1',
size=8, markersize=50, kind="kde",
scatter_color="r"):
with sns.axes_style("darkgrid"):
if xlabel and ylabel:
g = SubsampleJointGrid(xlabel, ylabel,
data=DataFrame(data={xlabel: x, ylabel: y}),
space=0.1, ratio=2, size=size, xlim=xlim, ylim=ylim)
else:
g = SubsampleJointGrid(x, y, size=size,
space=0.1, ratio=2, xlim=xlim, ylim=ylim)
g.plot_joint(sns.kdeplot, shade=True, cmap="Blues")
g.plot_sub_joint(plt.scatter, 1000, s=20, c=scatter_color, alpha=0.3)
g.plot_marginals(sns.distplot, kde=False, rug=False)
g.annotate(ss.pearsonr, fontsize=25, template="{stat} = {val:.2g}\np = {p:.2g}")
g.ax_joint.set_yticklabels(g.ax_joint.get_yticks())
g.ax_joint.set_xticklabels(g.ax_joint.get_xticks())
return g
示例2: customize
# 需要导入模块: import seaborn [as 别名]
# 或者: from seaborn import axes_style [as 别名]
def customize(func):
"""
修饰器,设置输出图像内容与风格
"""
@wraps(func)
def call_w_context(*args, **kwargs):
set_context = kwargs.pop("set_context", True)
if set_context:
color_palette = sns.color_palette("colorblind")
with plotting_context(), axes_style(), color_palette:
sns.despine(left=True)
return func(*args, **kwargs)
else:
return func(*args, **kwargs)
return call_w_context
示例3: axes_style
# 需要导入模块: import seaborn [as 别名]
# 或者: from seaborn import axes_style [as 别名]
def axes_style(style: str = "darkgrid", rc: dict = None):
"""
创建默认轴域风格
参数
---
:param style: seaborn 样式
:param rc: dict 配置标签
"""
if rc is None:
rc = {}
rc_default = {}
for name, val in rc_default.items():
rc.set_default(name, val)
return sns.axes_style(style=style, rc=rc)
示例4: plot_embedding
# 需要导入模块: import seaborn [as 别名]
# 或者: from seaborn import axes_style [as 别名]
def plot_embedding(embed:OrderedDict, feat:str, savename:Optional[str]=None, settings:PlotSettings=PlotSettings()) -> None:
r'''
Visualise weights in provided categorical entity-embedding matrix
Arguments:
embed: state_dict of trained nn.Embedding
feat: name of feature embedded
savename: Optional name of file to which to save the plot of feature importances
settings: :class:`~lumin.plotting.plot_settings.PlotSettings` class to control figure appearance
'''
with sns.axes_style(**settings.style):
plt.figure(figsize=(settings.w_small, settings.h_small))
sns.heatmap(to_np(embed['weight']), annot=True, fmt='.1f', linewidths=.5, cmap=settings.div_palette, annot_kws={'fontsize':settings.leg_sz})
plt.xlabel("Embedding", fontsize=settings.lbl_sz, color=settings.lbl_col)
plt.ylabel(feat, fontsize=settings.lbl_sz, color=settings.lbl_col)
plt.xticks(fontsize=settings.tk_sz, color=settings.tk_col)
plt.yticks(fontsize=settings.tk_sz, color=settings.tk_col)
plt.title(settings.title, fontsize=settings.title_sz, color=settings.title_col, loc=settings.title_loc)
if savename is not None: plt.savefig(settings.savepath/f'{savename}{settings.format}', bbox_inches='tight')
plt.show()
示例5: plot
# 需要导入模块: import seaborn [as 别名]
# 或者: from seaborn import axes_style [as 别名]
def plot(self):
r'''
Plots the history of the lr and momentum evolution as a function of iterations
'''
with sns.axes_style(self.plot_settings.style), sns.color_palette(self.plot_settings.cat_palette):
fig, axs = plt.subplots(2, 1, figsize=(self.plot_settings.w_mid, self.plot_settings.h_mid))
axs[1].set_xlabel("Iterations", fontsize=self.plot_settings.lbl_sz, color=self.plot_settings.lbl_col)
axs[0].set_ylabel("Learning Rate", fontsize=self.plot_settings.lbl_sz, color=self.plot_settings.lbl_col)
axs[1].set_ylabel("Momentum", fontsize=self.plot_settings.lbl_sz, color=self.plot_settings.lbl_col)
axs[0].plot(range(len(self.hist['lr'])), self.hist['lr'])
axs[1].plot(range(len(self.hist['mom'])), self.hist['mom'])
for ax in axs:
ax.tick_params(axis='x', labelsize=self.plot_settings.tk_sz, labelcolor=self.plot_settings.tk_col)
ax.tick_params(axis='y', labelsize=self.plot_settings.tk_sz, labelcolor=self.plot_settings.tk_col)
plt.show()
示例6: gauss_2d
# 需要导入模块: import seaborn [as 别名]
# 或者: from seaborn import axes_style [as 别名]
def gauss_2d(nsamples=1000):
"""
Another simple test plot
1d gaussian sampled from each sampler visualized as a joint 2d gaussian
"""
gaussian = TestGaussian(ndims=1)
control = HMCBase(distribution=gaussian)
experimental = MarkovJumpHMC(distribution=gaussian, resample=False)
with sns.axes_style("white"):
sns.jointplot(
control.sample(nsamples)[0],
experimental.sample(nsamples)[0],
kind='hex',
stat_func=None)
示例7: customize
# 需要导入模块: import seaborn [as 别名]
# 或者: from seaborn import axes_style [as 别名]
def customize(func):
@wraps(func)
def call_w_context(*args, **kwargs):
if not PlotConfig.FONT_SETTED:
_use_chinese(True)
set_context = kwargs.pop('set_context', True)
if set_context:
with plotting_context(), axes_style():
sns.despine(left=True)
return func(*args, **kwargs)
else:
return func(*args, **kwargs)
return call_w_context
示例8: start_plotting
# 需要导入模块: import seaborn [as 别名]
# 或者: from seaborn import axes_style [as 别名]
def start_plotting(fig_size, fig_pos, style="white", rc=None, despine=False):
with sns.axes_style(style, rc):
fig = plt.figure(figsize=fig_size)
if not fig_pos:
ax = fig.add_subplot(111)
else:
ax = fig.add_axes(fig_pos)
if despine:
sns.despine(left=True)
return fig, ax
示例9: plot_importance
# 需要导入模块: import seaborn [as 别名]
# 或者: from seaborn import axes_style [as 别名]
def plot_importance(df:pd.DataFrame, feat_name:str='Feature', imp_name:str='Importance', unc_name:str='Uncertainty', threshold:Optional[float]=None,
x_lbl:str='Importance via feature permutation', savename:Optional[str]=None, settings:PlotSettings=PlotSettings()) -> None:
r'''
Plot feature importances as computted via `get_nn_feat_importance`, `get_ensemble_feat_importance`, or `rf_rank_features`
Arguments:
df: DataFrame containing columns of features, importances and, optionally, uncertainties
feat_name: column name for features
imp_name: column name for importances
unc_name: column name for uncertainties (if present)
threshold: if set, will draw a line at the threshold hold used for feature importance
x_lbl: label to put on the x-axis
savename: Optional name of file to which to save the plot of feature importances
settings: :class:`~lumin.plotting.plot_settings.PlotSettings` class to control figure appearance
'''
with sns.axes_style(**settings.style), sns.color_palette(settings.cat_palette) as palette:
fig, ax = plt.subplots(figsize=(settings.w_large, (0.75)*settings.lbl_sz))
xerr = None if unc_name not in df else 'Uncertainty'
df.plot(feat_name, imp_name, 'barh', ax=ax, legend=False, xerr=xerr, error_kw={'elinewidth': 3}, color=palette[0])
if threshold is not None:
ax.axvline(x=threshold, label=f'Threshold {threshold}', color=palette[1], linestyle='--', linewidth=3)
plt.legend(loc=settings.leg_loc, fontsize=settings.leg_sz)
ax.set_xlabel(x_lbl, fontsize=settings.lbl_sz, color=settings.lbl_col)
ax.set_ylabel('Feature', fontsize=settings.lbl_sz, color=settings.lbl_col)
plt.xticks(fontsize=settings.tk_sz, color=settings.tk_col)
plt.yticks(fontsize=settings.tk_sz, color=settings.tk_col)
if savename is not None: plt.savefig(settings.savepath/f'{savename}{settings.format}')
plt.show()
示例10: plot_rank_order_dendrogram
# 需要导入模块: import seaborn [as 别名]
# 或者: from seaborn import axes_style [as 别名]
def plot_rank_order_dendrogram(df:pd.DataFrame, threshold:float=0.8, savename:Optional[str]=None, settings:PlotSettings=PlotSettings()) \
-> Dict[str,Union[List[str],float]]:
r'''
Plots a dendrogram of features in df clustered via Spearman's rank correlation coefficient.
Also returns a sets of features with correlation coefficients greater than the threshold
Arguments:
df: Pandas DataFrame containing data
threshold: Threshold on correlation coefficient
savename: Optional name of file to which to save the plot of feature importances
settings: :class:`~lumin.plotting.plot_settings.PlotSettings` class to control figure appearance
Returns:
Dict of sets of features with correlation coefficients greater than the threshold and cluster distance
'''
corr = np.round(scipy.stats.spearmanr(df).correlation, 4)
corr_condensed = hc.distance.squareform(1-np.abs(corr)) # Abs because negtaive of a feature is a trvial transformation: information unaffected
z = hc.linkage(corr_condensed, method='average', optimal_ordering=True)
with sns.axes_style('white'), sns.color_palette(settings.cat_palette):
plt.figure(figsize=(settings.w_large, (0.5*len(df.columns))))
hc.dendrogram(z, labels=df.columns, orientation='left', leaf_font_size=settings.lbl_sz, color_threshold=1-threshold)
plt.xlabel("Distance (1 - |Spearman's Rank Correlation Coefficient|)", fontsize=settings.lbl_sz, color=settings.lbl_col)
plt.xticks(fontsize=settings.tk_sz, color=settings.tk_col)
if savename is not None: plt.savefig(settings.savepath/f'{savename}{settings.format}', bbox_inches='tight')
plt.show()
feats = df.columns
sets = {}
for i, merge in enumerate(z):
if merge[2] > 1-threshold: continue
if merge[0] <= len(z): a = [feats[int(merge[0])]]
else: a = sets.pop(int(merge[0]))['children']
if merge[1] <= len(z): b = [feats[int(merge[1])]]
else: b = sets.pop(int(merge[1]))['children']
sets[1 + i + len(z)] = {'children': [*a, *b], 'distance': merge[2]}
return sets
示例11: plot_binary_class_pred
# 需要导入模块: import seaborn [as 别名]
# 或者: from seaborn import axes_style [as 别名]
def plot_binary_class_pred(df:pd.DataFrame, pred_name:str='pred', targ_name:str='gen_target', wgt_name:str=None, wgt_scale:float=1,
log_y:bool=False, lim_x:Tuple[float,float]=(0,1), density=True,
savename:Optional[str]=None, settings:PlotSettings=PlotSettings()) -> None:
r'''
Basic plotter for prediction distribution in a binary classification problem.
Note that labels are set using the settings.targ2class dictionary, which by default is {0: 'Background', 1: 'Signal'}.
Arguments:
df: DataFrame with targets and predictions
pred_name: name of column to use as predictions
targ_name: name of column to use as targets
wgt_name: optional name of column to use as sample weights
wgt_scale: applies a global multiplicative rescaling to sample weights. Default 1 = no rescaling
log_y: whether to use a log scale for the y-axis
lim_x: limit for plotting on the x-axis
density: whether to normalise each distribution to one, or keep set to sum of weights / datapoints
savename: Optional name of file to which to save the plot of feature importances
settings: :class:`~lumin.plotting.plot_settings.PlotSettings` class to control figure appearance
'''
with sns.axes_style(**settings.style), sns.color_palette(settings.cat_palette):
plt.figure(figsize=(settings.w_mid, settings.h_mid))
for targ in sorted(set(df[targ_name])):
cut = df[targ_name] == targ
hist_kws = {} if wgt_name is None else {'weights': wgt_scale*df.loc[cut, wgt_name]}
sns.distplot(df.loc[cut, pred_name], label=settings.targ2class[targ], hist_kws=hist_kws, norm_hist=density, kde=False)
plt.legend(loc=settings.leg_loc, fontsize=settings.leg_sz)
plt.xlabel("Class prediction", fontsize=settings.lbl_sz, color=settings.lbl_col)
plt.xlim(lim_x)
if density: plt.ylabel(r"$\frac{1}{N}\ \frac{dN}{dp}$", fontsize=settings.lbl_sz, color=settings.lbl_col)
elif wgt_scale != 1: plt.ylabel(str(wgt_scale) + r"$\times\frac{dN}{dp}$", fontsize=settings.lbl_sz, color=settings.lbl_col)
else: plt.ylabel(r"$\frac{dN}{dp}$", fontsize=settings.lbl_sz, color=settings.lbl_col)
if log_y:
plt.yscale('log', nonposy='clip')
plt.grid(True, which="both")
plt.xticks(fontsize=settings.tk_sz, color=settings.tk_col)
plt.yticks(fontsize=settings.tk_sz, color=settings.tk_col)
plt.title(settings.title, fontsize=settings.title_sz, color=settings.title_col, loc=settings.title_loc)
if savename is not None: plt.savefig(settings.savepath/f'{savename}{settings.format}', bbox_inches='tight')
plt.show()
示例12: plot_train_history
# 需要导入模块: import seaborn [as 别名]
# 或者: from seaborn import axes_style [as 别名]
def plot_train_history(histories:List[Dict[str,List[float]]], savename:Optional[str]=None, ignore_trn=True, settings:PlotSettings=PlotSettings(),
show:bool=True) -> None:
r'''
Plot histories object returned by :meth:`~lumin.nn.training.fold_train.fold_train_ensemble` showing the loss evolution over time per model trained.
Arguments:
histories: list of dictionaries mapping loss type to values at each (sub)-epoch
savename: Optional name of file to which to save the plot of feature importances
ignore_trn: whether to ignore training loss
settings: :class:`~lumin.plotting.plot_settings.PlotSettings` class to control figure appearance
show: whether or not to show the plot, or just save it
'''
with sns.axes_style(**settings.style), sns.color_palette(settings.cat_palette) as palette:
plt.figure(figsize=(settings.w_mid, settings.h_mid))
for i, history in enumerate(histories):
if i == 0:
for j, l in enumerate(history):
if not('trn' in l and ignore_trn): plt.plot(history[l], color=palette[j], label=_lookup_name(l))
else:
for j, l in enumerate(history):
if not('trn' in l and ignore_trn): plt.plot(history[l], color=palette[j])
plt.legend(loc=settings.leg_loc, fontsize=settings.leg_sz)
plt.xticks(fontsize=settings.tk_sz, color=settings.tk_col)
plt.yticks(fontsize=settings.tk_sz, color=settings.tk_col)
plt.xlabel("Epoch", fontsize=settings.lbl_sz, color=settings.lbl_col)
plt.ylabel("Loss", fontsize=settings.lbl_sz, color=settings.lbl_col)
if savename is not None: plt.savefig(f'{savename}{settings.format}', bbox_inches='tight')
if show: plt.show()
示例13: reset
# 需要导入模块: import seaborn [as 别名]
# 或者: from seaborn import axes_style [as 别名]
def reset(self) -> None:
r'''
Resets/initialises the logger's values and plots, and produces a placeholder plot. Should be called prior to `update_vals` or `update_plot`.
'''
self.loss_vals, self.vel_vals, self.gen_vals = [[] for _ in self.loss_names], [[] for _ in self.loss_names], [[] for _ in range(len(self.loss_names)-1)]
self.mean_losses = [None for _ in self.loss_names]
self.subepochs, self.epochs = [0], [0]
self.count,self.log = 1,False
with sns.axes_style(**self.settings.style):
if self.extra_detail:
self.fig = plt.figure(figsize=(self.settings.w_mid, self.settings.h_mid), constrained_layout=True)
gs = self.fig.add_gridspec(2, 3)
self.loss_ax = self.fig.add_subplot(gs[:,:-1])
self.vel_ax = self.fig.add_subplot(gs[:1,2:])
self.gen_ax = self.fig.add_subplot(gs[1:2,2:])
for ax in [self.loss_ax, self.vel_ax, self.gen_ax]:
ax.tick_params(axis='x', labelsize=0.8*self.settings.tk_sz, labelcolor=self.settings.tk_col)
ax.tick_params(axis='y', labelsize=0.8*self.settings.tk_sz, labelcolor=self.settings.tk_col)
self.loss_ax.set_xlabel('Sub-Epoch', fontsize=0.8*self.settings.lbl_sz, color=self.settings.lbl_col)
self.loss_ax.set_ylabel('Loss', fontsize=0.8*self.settings.lbl_sz, color=self.settings.lbl_col)
self.vel_ax.set_ylabel(r'$\Delta \bar{L}\ /$ Epoch', fontsize=0.8*self.settings.lbl_sz, color=self.settings.lbl_col)
self.gen_ax.set_xlabel('Epoch', fontsize=0.8*self.settings.lbl_sz, color=self.settings.lbl_col)
self.gen_ax.set_ylabel('Validation / Train', fontsize=0.8*self.settings.lbl_sz, color=self.settings.lbl_col)
self.display = display(self.fig, display_id=True)
else:
self.fig, self.loss_ax = plt.subplots(1, figsize=(self.settings.w_mid, self.settings.h_mid))
self.loss_ax.tick_params(axis='x', labelsize=0.8*self.settings.tk_sz, labelcolor=self.settings.tk_col)
self.loss_ax.tick_params(axis='y', labelsize=0.8*self.settings.tk_sz, labelcolor=self.settings.tk_col)
self.loss_ax.set_xlabel('Sub-Epoch', fontsize=0.8*self.settings.lbl_sz, color=self.settings.lbl_col)
self.loss_ax.set_ylabel('Loss', fontsize=0.8*self.settings.lbl_sz, color=self.settings.lbl_col)
self.display = display(self.loss_ax.figure, display_id=True)
示例14: plot_lr
# 需要导入模块: import seaborn [as 别名]
# 或者: from seaborn import axes_style [as 别名]
def plot_lr(self) -> None:
r'''
Plot the LR as a function of iterations.
'''
with sns.axes_style(self.plot_settings.style), sns.color_palette(self.plot_settings.cat_palette):
plt.figure(figsize=(self.plot_settings.h_small, self.plot_settings.h_small))
plt.plot(range(len(self.history['lr'])), self.history['lr'])
plt.xticks(fontsize=self.plot_settings.tk_sz, color=self.plot_settings.tk_col)
plt.yticks(fontsize=self.plot_settings.tk_sz, color=self.plot_settings.tk_col)
plt.ylabel("Learning rate", fontsize=self.plot_settings.lbl_sz, color=self.plot_settings.lbl_col)
plt.xlabel("Iterations", fontsize=self.plot_settings.lbl_sz, color=self.plot_settings.lbl_col)
plt.show()
示例15: main
# 需要导入模块: import seaborn [as 别名]
# 或者: from seaborn import axes_style [as 别名]
def main(args):
distance_confidence_info = pickle.load(open(osp.join(args.result_path, "distance_confidence_info.pkl"), "rb"))
margin_confidence_info = pickle.load(open(osp.join(args.result_path, "margin_confidence_info.pkl"), "rb"))
random_info = pickle.load(open(osp.join(args.result_path, "random_info.pkl"), "rb"))
distance_confidence_info['CMCs'] = [cmc * 100 for cmc in distance_confidence_info['CMCs']]
margin_confidence_info['CMCs'] = [cmc * 100 for cmc in margin_confidence_info['CMCs']]
random_info['CMCs'] = [cmc * 100 for cmc in random_info['CMCs']]
with sns.axes_style("white"):
fig = plt.figure(figsize=(6, 4.5))
ax = fig.add_subplot(111)
ax.plot(random_info['resulted_budgets'], random_info['CMCs'], marker='.', linewidth=2.5, markersize=0, label="DaRe(R)+RE (random)", color=flatui[0])
ax.plot(distance_confidence_info['resulted_budgets'], distance_confidence_info['CMCs'], marker='*', linewidth=2.5, markersize=0, label="DaRe(R)+RE (distance)", color=flatui[1])
ax.plot(margin_confidence_info['resulted_budgets'], margin_confidence_info['CMCs'], marker='*', linewidth=2.5, markersize=0, label="DaRe(R)+RE (margin)", color=flatui[2])
ax.scatter(SVDNet_R_RE[0], SVDNet_R_RE[1], marker='*', s=150, label="SVDNet(R)+RE", color=flatui[3])
ax.scatter(IDE_R_KISSME[0], IDE_R_KISSME[1], marker='h', s=100, label="IDE(R)+KISSME", color=flatui[4])
ax.scatter(IDE_C_KISSME[0], IDE_C_KISSME[1], marker='o', s=100, label="IDE(C)+KISSME", color=flatui[5])
ax.scatter(TriNet_R[0], TriNet_R[1], marker='D', s=60, label="TriNet(R)", color=flatui[6])
ax.scatter(SVDNet_C[0], SVDNet_C[1], marker='p', s=100, label="SVDNet(C)", color=flatui[7])
plt.xlabel("Average Budget (in MUL-ADD)", size=15)
plt.ylabel("CMC Rank 1 Accuracy (\%)", size=15)
handles, labels = ax.get_legend_handles_labels()
label_order = ['TriNet(R)', 'SVDNet(C)', 'SVDNet(R)+RE', 'IDE(R)+KISSME', 'IDE(C)+KISSME', 'DaRe(R)+RE (random)', 'DaRe(R)+RE (distance)', 'DaRe(R)+RE (margin)']
new_handles = []
for l in label_order:
for i in range(len(labels)):
if labels[i] == l:
new_handles.append(handles[i])
ax.legend(new_handles, label_order, loc='lower right')
plt.grid(linestyle='dotted')
plt.tight_layout(pad=1, w_pad=1, h_pad=1)
plt.xlim(3e8, 4.5e9)
plt.ylim(55, 95)
plt.savefig(args.figname + ".pdf", bbox_inches='tight')
plt.close()