本文整理匯總了Python中seaborn.violinplot方法的典型用法代碼示例。如果您正苦於以下問題:Python seaborn.violinplot方法的具體用法?Python seaborn.violinplot怎麽用?Python seaborn.violinplot使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類seaborn
的用法示例。
在下文中一共展示了seaborn.violinplot方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: quality_over_time
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import violinplot [as 別名]
def quality_over_time(dfs, path, figformat, title, plot_settings={}):
time_qual = Plot(path=path + "TimeQualityViolinPlot." + figformat,
title="Violin plot of quality over time")
sns.set(style="white", **plot_settings)
ax = sns.violinplot(x="timebin",
y="quals",
data=dfs,
inner=None,
cut=0,
linewidth=0)
ax.set(xlabel='Interval (hours)',
ylabel="Basecall quality",
title=title or time_qual.title)
plt.xticks(rotation=45, ha='center', fontsize=8)
time_qual.fig = ax.get_figure()
time_qual.save(format=figformat)
plt.close("all")
return time_qual
示例2: sequencing_speed_over_time
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import violinplot [as 別名]
def sequencing_speed_over_time(dfs, path, figformat, title, plot_settings={}):
time_duration = Plot(path=path + "TimeSequencingSpeed_ViolinPlot." + figformat,
title="Violin plot of sequencing speed over time")
sns.set(style="white", **plot_settings)
if "timebin" not in dfs:
dfs['timebin'] = add_time_bins(dfs)
mask = dfs['duration'] != 0
ax = sns.violinplot(x=dfs.loc[mask, "timebin"],
y=dfs.loc[mask, "lengths"] / dfs.loc[mask, "duration"],
inner=None,
cut=0,
linewidth=0)
ax.set(xlabel='Interval (hours)',
ylabel="Sequencing speed (nucleotides/second)",
title=title or time_duration.title)
plt.xticks(rotation=45, ha='center', fontsize=8)
time_duration.fig = ax.get_figure()
time_duration.save(format=figformat)
plt.close("all")
return time_duration
示例3: violin_jitter
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import violinplot [as 別名]
def violin_jitter(X, genes, gene, labels, focus, background=None,
xlabels=None):
gidx = list(genes).index(gene)
focus_idx = focus == labels
if background is None:
background_idx = focus != labels
else:
background_idx = background == labels
if xlabels is None:
xlabels = [ 'Background', 'Focus' ]
x_gene = X[:, gidx].toarray().flatten()
x_focus = x_gene[focus_idx]
x_background = x_gene[background_idx]
plt.figure()
sns.violinplot(data=[ x_focus, x_background ], scale='width', cut=0)
sns.stripplot(data=[ x_focus, x_background ], jitter=True, color='black', size=1)
plt.xticks([0, 1], xlabels)
plt.savefig('{}_violin_{}.png'.format(NAMESPACE, gene))
示例4: violinplot
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import violinplot [as 別名]
def violinplot(set_size, p_error, subplot, i):
"""Make learning cuves with violinplot.
Parameters
----------
set_size : list
Size of sub-set of data/features which the model is based on.
p_error : list
The prediction error for plain vanilla ridge.
subplot : int
Which subplot being produced.
i : int
Which iteration in the featureselection.
"""
plt.figure(1)
plt.subplot(int("22" + str(subplot))).set_title('Feature size ' + str(i),
loc='left')
plt.legend(loc='upper right')
plt.ylabel('Prediction error')
plt.xlabel('Data size')
sns.violinplot(x=set_size, y=p_error, scale="count")
sns.pointplot(x=set_size, y=p_error, ci=100, capsize=.2)
if subplot == 4:
plt.show()
示例5: featselect_featvar_plot
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import violinplot [as 別名]
def featselect_featvar_plot(p_error_select, number_feat):
"""Create learning curve with data size and prediction error.
Parameters
----------
data_size : list
Data_size for where the prediction were made.
p_error : list
Error for where the prediction were made.
data_size_mean : list
Mean of the data size in a sub-set.
p_error_mean : list
The mean error for the sub-set.
corrected_std : array
The standard deaviation for the sub-set of data.
"""
fig = plt.figure()
fig.add_subplot(111)
sns.violinplot(x=number_feat, y=p_error_select, scale="count")
sns.pointplot(x=number_feat, y=p_error_select)
plt.legend(loc='upper right')
plt.ylabel('Prediction error')
plt.xlabel('Data size')
plt.show()
示例6: metal_distance_widget
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import violinplot [as 別名]
def metal_distance_widget(df_concat):
'''Plot an violinplot of metal-element distances with ipywidgets
Parameters
----------
df_concat : Dataframe
dataframe of metal-elements distances
'''
metals = df_concat['Metal'].unique().tolist()
m_widget = Dropdown(options = metals, description = "Metals")
def metal_distance_violinplot(metal):
df_metal = df_concat[df_concat["Metal"] == metal].copy()
df_metal['Element'] = df_metal['Element'].apply(lambda x: metal+"-"+x)
# Set fonts
fig, ax = plt.subplots()
fig.set_size_inches(15,6)
subplot = sns.violinplot(x="Element", y="Distance", palette="muted", data=df_metal, ax=ax)
subplot.set(xlabel="Metal Interactions", ylabel="Distance", title=f"{metal} to Elements Distances Violin Plot")
return interact(metal_distance_violinplot, metal=m_widget);
示例7: bar_box_violin_dot_plots
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import violinplot [as 別名]
def bar_box_violin_dot_plots(data, category_col, numeric_col, axes, file_name=None):
sns.barplot(category_col, numeric_col, data=data, ax=axes[0])
sns.boxplot(
category_col, numeric_col, data=data[data[numeric_col].notnull()], ax=axes[2]
)
sns.violinplot(
category_col,
numeric_col,
data=data,
kind="violin",
inner="quartile",
scale="count",
split=True,
ax=axes[3],
)
sns.stripplot(category_col, numeric_col, data=data, jitter=True, ax=axes[1])
sns.despine(left=True)
示例8: fig6
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import violinplot [as 別名]
def fig6():
""" violin plot for the physicochemical proerties comparison.
A: molecules generated by pre-trained model v.s. ZINC set.
B: molecules generated by fine-tuned model v.s. A2AR set.
"""
plt.figure(figsize=(12, 6))
plt.subplot(121)
sns.set(style="white", palette="pastel", color_codes=True)
df = properties(['data/ZINC_B.txt', 'mol_p.txt'], ['ZINC Dataset', 'Pre-trained Model'])
sns.violinplot(x='Property', y='Number', hue='Set', data=df, linewidth=1, split=True, bw=1)
sns.despine(left=True)
plt.ylim([0.0, 18.0])
plt.xlabel('Structural Properties')
plt.subplot(122)
df = properties(['data/CHEMBL251.txt', 'mol_ex.txt'], ['A2AR Dataset', 'Fine-tuned Model'])
sns.set(style="white", palette="pastel", color_codes=True)
sns.violinplot(x='Property', y='Number', hue='Set', data=df, linewidth=1, split=True, bw=1)
sns.despine(left=True)
plt.ylim([0.0, 18.0])
plt.xlabel('Structural Properties')
plt.tight_layout()
plt.savefig('Figure_6.tif', dpi=300)
示例9: fig9
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import violinplot [as 別名]
def fig9():
""" violin plot for the physicochemical proerties comparison.
1: molecules generated by DrugEx with pre-trained model as exploration network.
2: molecules generated by DrugEx with fine-tuned model as exploration network.
"""
fig = plt.figure(figsize=(12, 12))
ax1 = fig.add_subplot(211)
sns.set(style="white", palette="pastel", color_codes=True)
df = properties(mol_paths + real_path, labels + real_label, is_active=True)
sns.violinplot(x='Property', y='Number', hue='Set', data=df, linewidth=1, bw=0.8)
sns.despine(left=True)
ax1.set(ylim=[0.0, 15.0], xlabel='Structural Properties')
ax2 = fig.add_subplot(212)
df = properties(mol_paths1 + real_path, labels + real_label, is_active=True)
sns.set(style="white", palette="pastel", color_codes=True)
sns.violinplot(x='Property', y='Number', hue='Set', data=df, linewidth=1, bw=0.8)
sns.despine(left=True)
ax2.set(ylim=[0.0, 15.0], xlabel='Structural Properties')
fig.tight_layout()
fig.savefig('Figure_9.tif', dpi=300)
示例10: plot_change_by_pos
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import violinplot [as 別名]
def plot_change_by_pos(diffs_by_context,plottype='box'):
fig = plt.figure(figsize=(6,4))
changes_by_position = {'position':[],'base':[],'diff':[]}
for lab in diffs_by_context:
for context in diffs_by_context[lab]:
for entry in diffs_by_context[lab][context]:
for pos,diff in enumerate(entry[:-1]):
changes_by_position['position'].append(pos+1)
changes_by_position['base'].append(lab)
changes_by_position['diff'].append(diff)
dPos = pd.DataFrame(changes_by_position)
if plottype == 'box':
sns.boxplot(x="position", y="diff", hue="base", data=dPos, palette=[cols[base],cols[methbase]])
elif plottype == 'violin':
sns.violinplot(x="position",y="diff", hue="base", data=dPos, palette=[cols[base],cols[methbase]])
sns.despine(trim=False)
plt.xlabel('Adenine Position in 6-mer')
plt.ylabel('Measured - Expected Current (pA)')
plt.ylim([-20,20])
plt.legend(title='',loc='upper center', bbox_to_anchor=(0.5, 1.05),
ncol=3, fancybox=True)
plt.savefig('change_by_position_box.pdf',transparent=True,dpi=500, bbox_inches='tight')
示例11: length_over_time
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import violinplot [as 別名]
def length_over_time(dfs, path, figformat, title, log_length=False, plot_settings={}):
if log_length:
time_length = Plot(path=path + "TimeLogLengthViolinPlot." + figformat,
title="Violin plot of log read lengths over time")
else:
time_length = Plot(path=path + "TimeLengthViolinPlot." + figformat,
title="Violin plot of read lengths over time")
sns.set(style="white", **plot_settings)
if log_length:
length_column = "log_lengths"
else:
length_column = "lengths"
if "length_filter" in dfs: # produced by NanoPlot filtering of too long reads
temp_dfs = dfs[dfs["length_filter"]]
else:
temp_dfs = dfs
ax = sns.violinplot(x="timebin",
y=length_column,
data=temp_dfs,
inner=None,
cut=0,
linewidth=0)
ax.set(xlabel='Interval (hours)',
ylabel="Read length",
title=title or time_length.title)
if log_length:
ticks = [10**i for i in range(10) if not 10**i > 10 * np.amax(dfs["lengths"])]
ax.set(yticks=np.log10(ticks),
yticklabels=ticks)
plt.xticks(rotation=45, ha='center', fontsize=8)
time_length.fig = ax.get_figure()
time_length.save(format=figformat)
plt.close("all")
return time_length
示例12: astro_oligo_violin
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import violinplot [as 別名]
def astro_oligo_violin(X, genes, gene, labels, name):
X = X.toarray()
gidx = list(genes).index(gene)
astro = X[labels == 'astro', gidx]
oligo = X[labels == 'oligo', gidx]
both = X[labels == 'both', gidx]
plt.figure()
sns.violinplot(data=[ astro, oligo, both ], scale='width', cut=0)
sns.stripplot(data=[ astro, oligo, both ], jitter=True, color='black', size=1)
plt.xticks([0, 1, 2], ['Astrocytes', 'Oligodendrocytes', 'Both'])
plt.savefig('{}_violin_{}.svg'.format(name, gene))
示例13: horizontal_violin_plot
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import violinplot [as 別名]
def horizontal_violin_plot(data, ordered_genomes, title, xlabel, pdf, hue=None, x=None, y=None, xlim=None):
"""not so generic function that specifically produces a paired boxplot/violinplot"""
fig, ax = plt.subplots()
sns.violinplot(data=data, x=x, y=y, hue=hue, order=ordered_genomes, palette=choose_palette(ordered_genomes),
saturation=boxplot_saturation, orient='h', cut=0, scale='count', ax=ax)
fig.suptitle(title)
ax.set_xlabel(xlabel)
if xlim is not None:
ax.set_xlim(xlim)
multipage_close(pdf, tight_layout=False)
示例14: run_kruskal
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import violinplot [as 別名]
def run_kruskal(df, condition_col, value_col='acc_diff', min_n_obs=6,
plot=False):
"""Run Kruskal-Wallis analysis of variance test.
Args:
df (pd.DataFrame): dataframe where each row is a paper.
condition_col (str): name of column to use as condition.
Keyword Args:
value_col (str): name of column to use as the numerical value to run the
test on.
min_n_obs (int): minimum number of observations in each sample in order
to run the test.
Returns:
(float): U statistic
(float): p-value
"""
data = [i for name, i in df.groupby(condition_col)[value_col]
if len(i) >= min_n_obs]
if len(data) > 2:
stat, p = kruskal(*data)
else:
stat, p = np.nan, np.nan
print('Not enough samples with more than {} observations.'.format(min_n_obs))
if plot:
enough_samples = df[condition_col].value_counts() >= min_n_obs
enough_samples = enough_samples.index[enough_samples].tolist()
fig, ax = plt.subplots()
sns.violinplot(
data=df[df[condition_col].isin(enough_samples)], x=condition_col,
y=value_col, ax=ax)
ax.set_title('Kruskal-Wallis for {} vs. {}\n(pvalue={:0.4f})'.format(
condition_col, value_col, p))
else:
fig = None
return {'test': 'kruskal', 'pvalue': p, 'stat': stat, 'fig': fig}
示例15: generate_molecules_plot
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import violinplot [as 別名]
def generate_molecules_plot(self):
# Correlation plot by molecules.
plt.close('all')
data_ordered_by_mol_ID = self.data.sort_values(["Molecule ID"], ascending=["True"])
sns.set(rc={'figure.figsize': (8.27,11.7)})
sns.violinplot(y='Molecule ID', x='$\Delta$logP error (calc - exp)', data=data_ordered_by_mol_ID,
inner='point', linewidth=1, width=1.2)
plt.tight_layout()
# plt.show()
plt.savefig(os.path.join(self.output_directory_path, self.LOGP_CORRELATION_PLOT_BY_LOGP_PATH_DIR))