简体   繁体   中英

Seaborn lmplot annotate correlation

How can I annotate text in lmplot ? I'd like to show the correlation between "petal_length" and the other features in the iris dataset, so I plotted regresion plots with 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 However, I don't know how to annotate the correlation values. I can do it with a single regplot , like this:

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 returns a FacetGrid, so I'd have to annotate the text on each of the axes. How can I annotate a list of values on a 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]

You could loop through the axes, calculate the r-value and add it to a legend:

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: Instead of creating a legend, you could also update the title, eg.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM