本文整理匯總了Python中seaborn.jointplot方法的典型用法代碼示例。如果您正苦於以下問題:Python seaborn.jointplot方法的具體用法?Python seaborn.jointplot怎麽用?Python seaborn.jointplot使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類seaborn
的用法示例。
在下文中一共展示了seaborn.jointplot方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: astro_oligo_joint
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import jointplot [as 別名]
def astro_oligo_joint(X, genes, gene1, gene2, labels, focus, name):
X = X.toarray()
gidx1 = list(genes).index(gene1)
gidx2 = list(genes).index(gene2)
idx = labels == focus
x1 = X[(idx, gidx1)]
x2 = X[(idx, gidx2)]
plt.figure()
sns.jointplot(
x1, x2, kind='scatter', space=0, alpha=0.3
).plot_joint(sns.kdeplot, zorder=0, n_levels=10)
plt.savefig('{}_joint_{}_{}_{}.png'.format(name, focus, gene1, gene2))
示例2: jointplot
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import jointplot [as 別名]
def jointplot(self, other, column, **kwargs):
"""
Generate a seaborn jointplot for given column in asset compared to
another asset.
Parameters:
- other: The other asset's dataframe
- column: The column name to use for the comparison.
- kwargs: Keyword arguments to pass down to `sns.pairplot()`
Returns:
A seaborn jointplot
"""
return sns.jointplot(
x=self.data[column],
y=other[column],
**kwargs
)
示例3: produce_the_kde_plot
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import jointplot [as 別名]
def produce_the_kde_plot(cycles, color, save_name):
ground_truth_and_suggested = [(eval_code.get_best_qed_from_smiles_bag(elem['ground_truth_product']),
eval_code.get_best_qed_from_smiles_bag(elem['suggested_product']))
for elem in cycles]
len_out = len(ground_truth_and_suggested)
ground_truth_and_suggested = [elem for elem in ground_truth_and_suggested if elem[1] != -np.inf]
len_filter = len(ground_truth_and_suggested)
num_discarding = len_out - len_filter
if num_discarding:
warnings.warn(f"Discarding {num_discarding} our of {len_out} as no successful reconstruction")
ground_truth_and_suggested = np.array(ground_truth_and_suggested)
ground_truth_product_qed = ground_truth_and_suggested[:, 0]
suggested_product_qed = ground_truth_and_suggested[:, 1]
g = sns.jointplot(x=ground_truth_product_qed, y=suggested_product_qed, kind="kde", color=color,
)
g.set_axis_labels("product's QED", "reconstructed product's QED", fontsize=16)
rsquare = lambda a, b: stats.pearsonr(ground_truth_product_qed, suggested_product_qed)[0] ** 2
g = g.annotate(rsquare, template="{stat}: {val:.2f}",
stat="$R^2$", loc="upper left", fontsize=12)
print(f"Rsquare: {stats.pearsonr(ground_truth_product_qed, suggested_product_qed)[0] ** 2}")
print(f"scipystats: {stats.linregress(ground_truth_product_qed, suggested_product_qed)}")
plt.tight_layout()
plt.savefig(f"{save_name}.pdf")
示例4: gauss_2d
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import jointplot [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)
示例5: visualize_distribution
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import jointplot [as 別名]
def visualize_distribution(X,prediction,score,path=None):
"""
Visualize the original density distribution of the data in 2-dimension space.
Parameters
----------
X: numpy array of shape (n_test, n_features)
Test data.
prediction: numpy array of shape (n_test, )
The prediction result of the test data.
score: numpy array of shape (n_test, )
The outlier score of the test data.
path: string
The saving path for result figures.
"""
sns.set(style="ticks")
X=X.to_numpy()
X_embedding = TSNE(n_components=2).fit_transform(X)
sns_plot=sns.jointplot(X_embedding[:,1],X_embedding[:,0], kind="kde", space=0, color="#4CB391")
if path:
sns_plot.savefig(path+'/distribution.png')
plt.show()
示例6: plot_trajectories
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import jointplot [as 別名]
def plot_trajectories(rewards, health, figure_file_obj):
plt.figure()
g = sns.jointplot(x=rewards, y=health, kind='kde')
g.plot_joint(plt.scatter, c='grey', s=30, linewidth=1, marker='+')
g.ax_joint.collections[0].set_alpha(0)
g.set_axis_labels('$Reward$', '$Health$')
if figure_file_obj:
plt.savefig(figure_file_obj, format='png')
else:
plt.show()
示例7: plot_correlation
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import jointplot [as 別名]
def plot_correlation(x, y, data, title=None, color=None, kind='joint', ax=None):
# Extract only logP values.
data = data[[x, y]]
# Find extreme values to make axes equal.
min_limit = np.ceil(min(data.min()) - 1)
max_limit = np.floor(max(data.max()) + 1)
axes_limits = np.array([min_limit, max_limit])
if kind == 'joint':
grid = sns.jointplot(x=x, y=y, data=data,
kind='reg', joint_kws={'ci': None}, stat_func=None,
xlim=axes_limits, ylim=axes_limits, color=color)
ax = grid.ax_joint
grid.fig.subplots_adjust(top=0.95)
grid.fig.suptitle(title)
elif kind == 'reg':
ax = sns.regplot(x=x, y=y, data=data, color=color, ax=ax)
ax.set_title(title)
# Add diagonal line.
ax.plot(axes_limits, axes_limits, ls='--', c='black', alpha=0.8, lw=0.7)
# Add shaded area for 0.5-1 logP error.
palette = sns.color_palette('BuGn_r')
ax.fill_between(axes_limits, axes_limits - 0.5, axes_limits + 0.5, alpha=0.2, color=palette[2])
ax.fill_between(axes_limits, axes_limits - 1, axes_limits + 1, alpha=0.2, color=palette[3])
示例8: plot_correlation
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import jointplot [as 別名]
def plot_correlation(x, y, data, title=None, color=None, kind='joint', ax=None):
# Extract only pKa values.
data = data[[x, y]]
# Find extreme values to make axes equal.
min_limit = np.ceil(min(data.min()) - 2)
max_limit = np.floor(max(data.max()) + 2)
axes_limits = np.array([min_limit, max_limit])
if kind == 'joint':
grid = sns.jointplot(x=x, y=y, data=data,
kind='reg', joint_kws={'ci': None}, stat_func=None,
xlim=axes_limits, ylim=axes_limits, color=color)
ax = grid.ax_joint
grid.fig.subplots_adjust(top=0.95)
grid.fig.suptitle(title)
elif kind == 'reg':
ax = sns.regplot(x=x, y=y, data=data, color=color, ax=ax)
ax.set_title(title)
# Add diagonal line.
ax.plot(axes_limits, axes_limits, ls='--', c='black', alpha=0.8, lw=0.7)
# Add shaded area for 0.5-1 pKa error.
palette = sns.color_palette('BuGn_r')
ax.fill_between(axes_limits, axes_limits - 0.5, axes_limits + 0.5, alpha=0.2, color=palette[2])
ax.fill_between(axes_limits, axes_limits - 1, axes_limits + 1, alpha=0.2, color=palette[3])
示例9: eval1
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import jointplot [as 別名]
def eval1():
n_observations = 2000 # number of data points
n_features = 1 # number of features
X_train, X_test, y_train, y_test = build_econ1_dataset(n_observations)
print("Size of features in training data: {}".format(X_train.shape))
print("Size of output in training data: {}".format(y_train.shape))
print("Size of features in test data: {}".format(X_test.shape))
print("Size of output in test data: {}".format(y_test.shape))
fig, ax = plt.subplots()
fig.set_size_inches(10, 8)
sns.regplot(X_train, y_train, fit_reg=False)
# plt.savefig('toydata.png')
# plt.show()
# plot.figure.size = 100
# plt.show()
kmn = KernelMixtureNetwork(train_scales=True, n_centers=20)
kmn.fit(X_train, y_train, n_epoch=300, eval_set=(X_test, y_test))
kmn.plot_loss()
# plt.savefig('trainplot.png')
samples = kmn.sample(X_test)
print(X_test.shape, samples.shape)
jp = sns.jointplot(X_test.ravel(), samples, kind="hex", stat_func=None, size=10)
jp.ax_joint.add_line(Line2D([X_test[0][0], X_test[0][0]], [-40, 40], linewidth=3))
jp.ax_joint.add_line(Line2D([X_test[1][0], X_test[1][0]], [-40, 40], color='g', linewidth=3))
jp.ax_joint.add_line(Line2D([X_test[2][0], X_test[2][0]], [-40, 40], color='r', linewidth=3))
plt.savefig('hexplot.png')
plt.show()
d = kmn.predict_density(X_test[0:3, :].reshape(-1, 1), resolution=1000)
df = pd.DataFrame(d).transpose()
df.index = np.linspace(kmn.y_min, kmn.y_max, num=1000)
df.plot(legend=False, linewidth=3, figsize=(12.2, 8))
plt.savefig('conditional_density.png')
示例10: saveMovg
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import jointplot [as 別名]
def saveMovg(df,step=12):
moving_avg = pd.rolling_mean(df['dsc_log'], step)
sns.jointplot(x=df['time'],y=moving_avg,color='red')
plt.title('Moving Average')
plt.savefig(ma_path)
# 創建word文檔
示例11: plot_euler
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import jointplot [as 別名]
def plot_euler(theta,phi,psi,plot_psi=True):
sns.jointplot(theta,phi,kind='hex',
xlim=(-180,180),
ylim=(0,180)).set_axis_labels("theta", "phi")
if plot_psi:
plt.figure()
plt.hist(psi)
plt.xlabel('psi')
示例12: hist_2d
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import jointplot [as 別名]
def hist_2d(distr, nsamples, **kwargs):
"""
Plots a 2d hexbinned histogram of distribution
Args:
distr: Distribution object
nsamples: number of samples to use to generate plot
"""
sampler = MarkovJumpHMC(distribution=distr, **kwargs)
samples = sampler.sample(nsamples)
with sns.axes_style("white"):
g = sns.jointplot(samples[0], samples[1], kind='kde', stat_func=None)
return g
示例13: sample_54_1
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import jointplot [as 別名]
def sample_54_1():
"""
5.4 使用seaborn可視化數據
:return:
"""
sns.distplot(tsla_df['p_change'], bins=80)
plt.show()
sns.boxplot(x='date_week', y='p_change', data=tsla_df)
plt.show()
sns.jointplot(tsla_df['high'], tsla_df['low'])
plt.show()
示例14: plot_pop_resids
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import jointplot [as 別名]
def plot_pop_resids(msm, **kwargs):
"""
Plot residuals between MSM populations and raw counts.
Parameters
----------
msm : msmbuilder.msm
MSMBuilder MarkovStateModel
**kwargs : dict, optional
Extra arguments to pass to seaborn.jointplot
Returns
-------
ax : matplotlib axis
matplotlib figure axis
"""
if hasattr(msm, 'all_populations_'):
msm_pop = msm.populations_.mean(0)
elif hasattr(msm, 'populations_'):
msm_pop = msm.populations_
raw_pop = msm.countsmat_.sum(1) / msm.countsmat_.sum()
ax = sns.jointplot(np.log10(raw_pop), np.log10(msm_pop), kind='resid',
**kwargs)
ax.ax_joint.set_xlabel('Raw Populations', size=20)
ax.ax_joint.set_ylabel('Residuals', size=20)
return ax
示例15: run
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import jointplot [as 別名]
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')
}