本文整理汇总了Python中seaborn.FacetGrid方法的典型用法代码示例。如果您正苦于以下问题:Python seaborn.FacetGrid方法的具体用法?Python seaborn.FacetGrid怎么用?Python seaborn.FacetGrid使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类seaborn
的用法示例。
在下文中一共展示了seaborn.FacetGrid方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_probplot_with_FacetGrid_with_markers
# 需要导入模块: import seaborn [as 别名]
# 或者: from seaborn import FacetGrid [as 别名]
def test_probplot_with_FacetGrid_with_markers(usemarkers):
iris = seaborn.load_dataset("iris")
hue_kws = None
species = sorted(iris['species'].unique())
markers = ['o', 'o', 'o']
if usemarkers:
markers = ['o', 's', '^']
hue_kws = {'marker': markers}
fg = (
seaborn.FacetGrid(data=iris, hue='species', hue_kws=hue_kws)
.map(viz.probplot, 'sepal_length')
.set_axis_labels(x_var='Probability', y_var='Sepal Length')
.add_legend()
)
_lines = filter(lambda x: isinstance(x, matplotlib.lines.Line2D), fg.ax.get_children())
result_markers = {
l.get_label(): l.get_marker()
for l in _lines
}
expected_markers = dict(zip(species, markers))
assert expected_markers == result_markers
示例2: plot_lc
# 需要导入模块: import seaborn [as 别名]
# 或者: from seaborn import FacetGrid [as 别名]
def plot_lc(lc, metrics=None, outputs=False):
lc = pd.melt(lc, id_vars=['split', 'epoch'], var_name='output')
if metrics:
if not isinstance(metrics, list):
metrics = [metrics]
tmp = '(%s)' % ('|'.join(metrics))
lc = lc.loc[lc.output.str.contains(tmp)]
metrics = lc.output[~lc.output.str.contains('_')].unique()
lc['metric'] = ''
for metric in metrics:
lc.loc[lc.output.str.contains(metric), 'metric'] = metric
lc.loc[lc.output == metric, 'output'] = 'mean'
lc.output = lc.output.str.replace('_%s' % metric, '')
lc.output = lc.output.str.replace('cpg_', '')
if outputs:
lc = lc.loc[lc.output != 'mean']
else:
lc = lc.loc[lc.output == 'mean']
grid = sns.FacetGrid(lc, col='split', row='metric', hue='output',
sharey=False, size=3, aspect=1.2, legend_out=True)
grid.map(mpl.pyplot.plot, 'epoch', 'value', linewidth=2)
grid.set(ylabel='')
grid.add_legend()
return grid
示例3: test_plot_rm_corr
# 需要导入模块: import seaborn [as 别名]
# 或者: from seaborn import FacetGrid [as 别名]
def test_plot_rm_corr(self):
"""Test plot_shift()."""
df = read_dataset('rm_corr')
g = plot_rm_corr(data=df, x='pH', y='PacO2', subject='Subject')
g = plot_rm_corr(data=df, x='pH', y='PacO2', subject='Subject',
legend=False)
assert isinstance(g, sns.FacetGrid)
plt.close('all')
示例4: plot_grid
# 需要导入模块: import seaborn [as 别名]
# 或者: from seaborn import FacetGrid [as 别名]
def plot_grid(self):
self._create_grid_df()
df = self.grid_df
#make maximum possible 500
df.loc[df['score']>500,'score'] = 500
#match plot
df_match = df[(df['mismatch_score'] == -2) & (df['gap_score'] == -1)]
g = sns.FacetGrid(df_match, col="match_score")
g = g.map(sns.boxplot, "match", "score")
sns.plt.ylim(0,400)
sns.plt.show()
#mismatch plot
df_mismatch = df[(df['match_score'] == 3) & (df['gap_score'] == -1)]
g = sns.FacetGrid(df_mismatch, col="mismatch_score")
g = g.map(sns.boxplot, "match", "score")
sns.plt.ylim(0,400)
sns.plt.show()
#gap plot
df_gap = df[(df['match_score'] == 3) & (df['mismatch_score'] == -2)]
g = sns.FacetGrid(df_gap, col="gap_score")
g = g.map(sns.boxplot, "match", "score")
sns.plt.ylim(0,400)
sns.plt.show()
示例5: plot_llk
# 需要导入模块: import seaborn [as 别名]
# 或者: from seaborn import FacetGrid [as 别名]
def plot_llk(train_elbo, test_elbo):
import matplotlib.pyplot as plt
import scipy as sp
import seaborn as sns
import pandas as pd
plt.figure(figsize=(30, 10))
sns.set_style("whitegrid")
data = np.concatenate([np.arange(len(test_elbo))[:, sp.newaxis], -test_elbo[:, sp.newaxis]], axis=1)
df = pd.DataFrame(data=data, columns=['Training Epoch', 'Test ELBO'])
g = sns.FacetGrid(df, size=10, aspect=1.5)
g.map(plt.scatter, "Training Epoch", "Test ELBO")
g.map(plt.plot, "Training Epoch", "Test ELBO")
plt.savefig(str(Path(result_dir, 'test_elbo_vae.png')))
plt.close('all')
示例6: plot
# 需要导入模块: import seaborn [as 别名]
# 或者: from seaborn import FacetGrid [as 别名]
def plot(data, column, column_order, ymax):
g = sns.FacetGrid(
data,
col=column,
col_order = column_order,
sharex=False,
size = 3.5,
aspect = .7
)
g.map(
sns.barplot,
"model", "GFLOP/s", "batch",
hue_order = list(set(data['batch'])).sort(),
order = list(set(data['batch'])).sort()
)
if ymax == 0:
ymax = 1
else:
plt.yticks(np.arange(0, ymax + (ymax * .1), ymax/10))
axes = np.array(g.axes.flat)
#hue_start = random.random()
for ax in axes:
#ax.hlines(.0003, -0.5, 0.5, linestyle='--', linewidth=1, color=getColor(hue_start, .6, .9))
ax.set_ylim(0, ymax)
return plt.gcf(), axes
示例7: errorplot
# 需要导入模块: import seaborn [as 别名]
# 或者: from seaborn import FacetGrid [as 别名]
def errorplot(x, y, minconf, maxconf, **kwargs):
'''
e.g.
g = sns.FacetGrid(attr, col='run', hue='subj_pos', col_wrap=5)
g = g.map(errorplot, 'n_diff_intervening', 'errorprob',
'minconf', 'maxconf').add_legend()
'''
plt.errorbar(x, y, yerr=[y - minconf, maxconf - y], fmt='o-', **kwargs)
示例8: plot_stats
# 需要导入模块: import seaborn [as 别名]
# 或者: from seaborn import FacetGrid [as 别名]
def plot_stats(stats):
stats = stats.sort_values('frac_obs', ascending=False)
stats = pd.melt(stats, id_vars=['output'], var_name='metric')
# stats = stats.loc[stats.metric.isin(['frac_obs', 'frac_one'])]
# stats.metric = stats.metric.str.replace('frac_obs', 'cov')
# stats.metric = stats.metric.str.replace('frac_one', 'met')
grid = sns.FacetGrid(data=stats, col='metric', sharex=False)
grid.map(sns.barplot, 'value', 'output')
for ax in grid.axes.ravel():
ax.set(xlabel='', ylabel='')
return grid
示例9: _plot_surface_points
# 需要导入模块: import seaborn [as 别名]
# 或者: from seaborn import FacetGrid [as 别名]
def _plot_surface_points(self, x, y, series_to_plot_i, aspect, extent, kwargs):
if series_to_plot_i.shape[0] != 0:
# size = fig.get_size_inches() * fig.dpi
# print(size)
# print(aspect)
try:
p = sns.FacetGrid(series_to_plot_i, hue="surface",
palette=self._color_lot,
ylim=[extent[2], extent[3]],
xlim=[extent[0], extent[1]],
legend_out=False,
aspect=aspect,
height=6)
except KeyError: # for kriging dataframes
p = sns.FacetGrid(series_to_plot_i, hue=None,
palette='k',
ylim=[extent[2], extent[3]],
xlim=[extent[0], extent[1]],
legend_out=False,
aspect=aspect,
height=6)
p.map(plt.scatter, x, y,
**kwargs['scatter_kws'],
zorder=10)
else:
self._show_legend = True
示例10: _plot_orientations
# 需要导入模块: import seaborn [as 别名]
# 或者: from seaborn import FacetGrid [as 别名]
def _plot_orientations(self, x, y, Gx, Gy, series_to_plot_f, min_axis, extent, p, aspect=None, ax=None):
if series_to_plot_f.shape[0] != 0:
# print('hello')
if p is False:
# size = fig.get_size_inches() * fig.dpi
# print('before plot orient', size)
surflist = list(series_to_plot_f['surface'].unique())
for surface in surflist:
to_plot = series_to_plot_f[series_to_plot_f['surface'] == surface]
plt.quiver(to_plot[x], to_plot[y],
to_plot[Gx], to_plot[Gy],
pivot="tail", scale_units=min_axis, scale=30, color=self._color_lot[surface],
edgecolor='k', headwidth=8, linewidths=1)
# ax.Axes.set_ylim([extent[2], extent[3]])
# ax.Axes.set_xlim([extent[0], extent[1]])
# fig = plt.gcf()
# fig.set_size_inches(20,10)
# if aspect is not None:
# ax = plt.gca()
# ax.set_aspect(aspect)
else:
p = sns.FacetGrid(series_to_plot_f, hue="surface",
palette=self._color_lot,
ylim=[extent[2], extent[3]],
xlim=[extent[0], extent[1]],
legend_out=False,
aspect=aspect,
height=6)
p.map(plt.quiver, x, y, Gx, Gy, pivot="tail", scale_units=min_axis, scale=10, edgecolor='k',
headwidth=4, linewidths=1)
else:
# print('no orient')
pass
# size = fig.get_size_inches() * fig.dpi
# print('after plot_orientations', size)
示例11: plot_facet_grid
# 需要导入模块: import seaborn [as 别名]
# 或者: from seaborn import FacetGrid [as 别名]
def plot_facet_grid(df, target, frow, fcol, tag='eda', directory=None):
r"""Plot a Seaborn faceted histogram grid.
Parameters
----------
df : pandas.DataFrame
The dataframe containing the features.
target : str
The target variable for contrast.
frow : list of str
Feature names for the row elements of the grid.
fcol : list of str
Feature names for the column elements of the grid.
tag : str
Unique identifier for the plot.
directory : str, optional
The full specification of the plot location.
Returns
-------
None : None.
References
----------
http://seaborn.pydata.org/generated/seaborn.FacetGrid.html
"""
logger.info("Generating Facet Grid")
# Calculate the number of bins using the Freedman-Diaconis rule.
tlen = len(df[target])
tmax = df[target].max()
tmin = df[target].min()
trange = tmax - tmin
iqr = df[target].quantile(Q3) - df[target].quantile(Q1)
h = 2 * iqr * (tlen ** (-1/3))
nbins = math.ceil(trange / h)
# Generate the pair plot
sns.set(style="darkgrid")
fg = sns.FacetGrid(df, row=frow, col=fcol, margin_titles=True)
bins = np.linspace(tmin, tmax, nbins)
fg.map(plt.hist, target, color="steelblue", bins=bins, lw=0)
# Save the plot
write_plot('seaborn', fg, 'facet_grid', tag, directory)
#
# Function plot_distribution
#
示例12: visualize_outlierscore
# 需要导入模块: import seaborn [as 别名]
# 或者: from seaborn import FacetGrid [as 别名]
def visualize_outlierscore(value,label,contamination,path=None):
"""
Visualize the predicted outlier score.
Parameters
----------
value: numpy array of shape (n_test, )
The outlier score of the test data.
label: numpy array of shape (n_test, )
The label of test data produced by the algorithm.
contamination : float in (0., 0.5), optional (default=0.1)
The amount of contamination of the data set,
i.e. the proportion of outliers in the data set. Used when fitting to
define the threshold on the decision function.
path: string
The saving path for result figures.
"""
sns.set(style="darkgrid")
ts = np.arange(len(value))
outlier_label=[]
for i in range(len(ts)):
if label[i]==1:
outlier_label.append('inlier')
else:
outlier_label.append('outlier')
X_outlier = pd.DataFrame({'ts':ts,'Outlier_score':value,'outlier_label':np.array(outlier_label)})
pal = dict(inlier="#4CB391", outlier="gray")
g = sns.FacetGrid(X_outlier, hue="outlier_label", palette=pal, height=5)
g.map(plt.scatter, "ts", "Outlier_score", s=30, alpha=.7, linewidth=.5, edgecolor="white")
ranking = np.sort(value)
threshold = ranking[int((1 - contamination) * len(ranking))]
plt.hlines(threshold, xmin=0, xmax=len(X_outlier)-1, colors="g", zorder=100, label='Threshold')
threshold = ranking[int((contamination) * len(ranking))]
plt.hlines(threshold, xmin=0, xmax=len(X_outlier)-1, colors="g", zorder=100, label='Threshold2')
if path:
plt.savefig(path+'/visualize_outlierscore.png')
plt.show()
# def visualize_outlierresult(X,label,path=None):
# """
# Visualize the predicted outlier result.
#
# Parameters
# ----------
# X: numpy array of shape (n_test, n_features)
# The test data.
# label: numpy array of shape (n_test, )
# The label of test data produced by the algorithm.
#
# """
# X['outlier']=pd.Series(label)
# pal = dict(inlier="#4CB391", outlier="gray")
# g = sns.pairplot(X, hue="outlier", palette=pal)
# if path:
# plt.savefig(path+'/visualize_outlierresult.png')
# plt.show()