mybins=np.logspace(0, np.log(100), 100)
g = sns.JointGrid(data1, data2, data, xlim=[.5, 1000000],
ylim=[.1, 10000000])
g.plot_marginals(sns.distplot, color='blue', bins=mybins)
g = g.plot(sns.regplot, sns.distplot)
g = g.annotate(stats.pearsonr)
ax = g.ax_joint
ax.set_xscale('log')
ax.set_yscale('log')
g.ax_marg_x.set_xscale('log')
g.ax_marg_y.set_yscale('log')
这个方法很好用。最后,我决定将表格的值转换为log(x)
,因为这样可以使图形更容易缩放和在短时间内可视化。
对于对数坐标的绘图,另一种方法是将log_scale
参数传递给jointplot
1的边缘组件,可以通过marginal_kws=
参数完成。
import seaborn as sns
from scipy import stats
data = sns.load_dataset('tips')[['tip', 'total_bill']]**3
graph = sns.jointplot(x='tip', y='total_bill', data=data, kind='reg', marginal_kws={'log_scale': True})
# ^^^^^^^^^^^^^ here
pearsonr, p = stats.pearsonr(data['tip'], data['total_bill'])
graph.ax_joint.annotate(f'pearsonr = {pearsonr:.2f}; p = {p:.0E}', xy=(35, 50));
请注意,相关系数是相同的,因为用于导出两条拟合线的基础回归函数是相同的。
尽管上面第一个图中的拟合线看起来不是线性的,但它确实是线性的,只是轴被对数缩放了,这“扭曲”了视图。在底层,sns.jointplot()
调用 sns.regplot()
来绘制散点图和拟合线,因此如果我们使用相同的数据并对数缩放轴调用它,我们将得到相同的图。换句话说,以下代码将产生相同的散点图。
sns.regplot(x='tip', y='total_bill', data=data).set(xscale='log', yscale='log');
jointplot()
之前对其进行对数处理,那么这将是完全不同的模型(您可能不想要它),因为现在回归系数将来自于log(y)=a+b*log(x)
而不是之前的y=a+b*x
。1 边际图使用 sns.histplot
绘制,该函数支持 log_scale
参数。
2 一个方便的函数用于绘制本文中的图形:
from scipy import stats
def plot_jointplot(x, y, data, xy=(0.4, 0.1), marginal_kws=None, figsize=(6,4)):
# compute pearsonr
pearsonr, p = stats.pearsonr(data[x], data[y])
# plot joint plot
graph = sns.jointplot(x=x, y=y, data=data, kind='reg', marginal_kws=marginal_kws)
# annotate the pearson r results
graph.ax_joint.annotate(f'pearsonr = {pearsonr:.2f}; p = {p:.0E}', xy=xy);
# set figsize
graph.figure.set_size_inches(figsize);
return graph
data = sns.load_dataset('tips')[['tip', 'total_bill']]**3
plot_jointplot('tip', 'total_bill', data, (50, 35), {'log_scale': True}) # log-scaled
plot_jointplot('tip', 'total_bill', data, (550, 3.5)) # linear-scaled
plot_jointplot('tip', 'total_bill', np.log(data), (3.5, 3.5)) # linear-scaled on log data