Seaborn jointplot 带有相关性注释

mak*_*kis 3 python matplotlib seaborn jointplot

在最新的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()
Run Code Online (Sandbox Code Playgroud)

我无法再得到的旧输出:

在此输入图像描述

Joh*_*anC 9

sns.jointplot不返回 an ax,而是返回 a 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()
Run Code Online (Sandbox Code Playgroud)

示例图