Seaborn jointplot 注释相关

Seaborn jointplot annotate with correlation

在发布最新的 seaborn 版本之前,我能够使用以下内容用 pearson Rho 注释我的情节。

使用最新版本我找不到方法来做同样的事情 #ax.annotate(stats.pearsonr) 抛出错误。

import matplotlib as mpl
import scipy.stats as stat
import matplotlib.pyplot as plt
import pandas as pd, numpy as np
import scipy.stats as stats
import seaborn as sns

X = np.random.rand(10,2)

df = pd.DataFrame(X, columns=['v1', 'v2'])

a = df.v1.values
b = a*2 + a**5

print("The Rho is {}".format(np.corrcoef(a,b)[0][1]))

ax = sns.jointplot(a, b, kind='reg',color='royalblue')
#ax.annotate(stats.pearsonr)
ax.ax_joint.scatter(a,b)
ax.set_axis_labels(xlabel='a', ylabel='b', size=15)
plt.tight_layout()
plt.show()

我再也无法获得的旧输出:

sns.jointplot 不是 return 一个 ax,而是一个 JointGrid。您可以使用 ax_jointax_marg_xax_marg_y 作为普通的 matplotlib 轴来更改子图,例如添加注释。

这里是一个使用轴分数坐标定位的例子。

import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as stats
import seaborn as sns

a = np.random.rand(10)
b = a * 2 + a ** 5

print("The Rho is {}".format(np.corrcoef(a, b)[0][1]))

g = sns.jointplot(x=a, y=b, kind='reg', color='royalblue')
# ax.annotate(stats.pearsonr)
r, p = stats.pearsonr(a, b)
g.ax_joint.annotate(f'$\rho = {r:.3f}, p = {p:.3f}$',
                    xy=(0.1, 0.9), xycoords='axes fraction',
                    ha='left', va='center',
                    bbox={'boxstyle': 'round', 'fc': 'powderblue', 'ec': 'navy'})
g.ax_joint.scatter(a, b)
g.set_axis_labels(xlabel='a', ylabel='b', size=15)
plt.tight_layout()
plt.show()