[英]Seaborn lmplot annotate correlation
如何在lmplot
中注释文本? 我想显示“petal_length”与 iris 数据集中其他特征之间的相关性,所以我用lmplot
绘制了回归图。
import seaborn as sns
import pandas as pd
df = sns.load_dataset('iris')
melt = pd.melt(df, id_vars=['species','petal_length'], value_vars=['sepal_length','sepal_width', 'petal_width'])
sns.lmplot(data=melt, x='value', y='petal_length', col='variable', sharey=False, sharex=False)
但是,我不知道如何注释相关值。 我可以用一个regplot
做到这一点,就像这样:
from scipy.stats import spearmanr
r, pvalue = spearmanr(df['sepal_length'], df['petal_length'])
sns.regplot(data=df, x='sepal_length', y='petal_length', label=f'Spearman = {r:.2f}')
plt.legend()
lmplot
返回一个 FacetGrid,所以我必须在每个轴上注释文本。 如何注释FacetGrid
上的值列表?
spearman = []
for feature in ['sepal_length','sepal_width', 'petal_width']:
r, pvalue = spearmanr(df['petal_length'], df[feature])
spearman.append(r)
print(spearman)
[0.8818981264349859,-0.30963508601557777,0.9376668235763412]
您可以遍历轴,计算 r 值并将其添加到图例中:
import seaborn as sns
import pandas as pd
from scipy.stats import spearmanr
from matplotlib import pyplot as plt
df = sns.load_dataset('iris')
melt = pd.melt(df, id_vars=['species', 'petal_length'], value_vars=['sepal_length', 'sepal_width', 'petal_width'])
g = sns.lmplot(data=melt, x='value', y='petal_length', col='variable', sharey=False, sharex=False)
for ax, feature in zip(g.axes.flat, g.col_names):
r, pvalue = spearmanr(df['petal_length'], df[feature])
ax.collections[0].set_label(f'Spearman = {r:.2f}')
ax.legend()
plt.tight_layout()
plt.show()
PS:除了创建图例,您还可以更新标题,例如。
ax.set_title(ax.get_title() + f', r={r:.2f}')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.