[英]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.