Seaborn lmplot注释相关性

2024-06-10 07:35:16 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在lmplot中注释文本?我想展示“花瓣长度”与虹膜数据集中其他特征之间的相关性,所以我用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)

lmplot 但是,我不知道如何注释相关值。我可以用一个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()

regplot

lmplot返回一个FaceGrid,因此我必须在每个轴上注释文本如何在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]


Tags: 文本importdfasvarswidthlengthpd
1条回答
网友
1楼 · 发布于 2024-06-10 07:35:16

可以在轴之间循环,计算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()

resulting plot

PS:除了创建图例,您还可以更新标题,例如

ax.set_title(ax.get_title() + f', r={r:.2f}')

相关问题 更多 >