首页 > 解决方案 > 如何在 seaborn lmplot 中注释回归线?

问题描述

我在 Seaborn 中绘制了两个变量,并使用hue关键字将变量分为两类。

我想用决定系数来注释每条回归线。此问题仅描述如何使用图例显示线条的标签。

 import pandas as pd 
 import seaborn as sns
 import matplotlib.pyplot as plt 

df = pd.read_excel(open('intubation data.xlsx', 'rb'), sheet_name='Data 
(pretest)', header=1, na_values='x')
vars_of_interest = ['PGY','Time (sec)','Aspirate (cc)']
df['Resident'] = df['PGY'] < 4

 lm = sns.lmplot(x=vars_of_interest[1], y=vars_of_interest[2],
        data=df, hue='Resident', robust=True, truncate=True,
        line_kws={'label':"bob"})

标签: pythonseaborn

解决方案


按原样使用您的代码:

 import pandas as pd 
 import seaborn as sns
 import matplotlib.pyplot as plt 

df = pd.read_excel(open('intubation data.xlsx', 'rb'), sheet_name='Data 
(pretest)', header=1, na_values='x')
vars_of_interest = ['PGY','Time (sec)','Aspirate (cc)']
df['Resident'] = df['PGY'] < 4

p = sns.lmplot(x=vars_of_interest[1], y=vars_of_interest[2],
        data=df, hue='Resident', robust=True, truncate=True,
        line_kws={'label':"bob"}, legend=True)
# assuming you have 2 groups
ax = p.axes[0, 0]
ax.legend()
leg = ax.get_legend()
L_labels = leg.get_texts()
# assuming you computed r_squared which is the coefficient of determination somewhere else
label_line_1 = r'$R^2:{0:.2f}$'.format(0.3)
label_line_2 = r'$R^2:{0:.2f}$'.format(0.21)
L_labels[0].set_text(label_line_1)
L_labels[1].set_text(label_line_2)

瞧:使用我自己的随机数据创建的图表,因为 OP 没有提供任何数据。 在此处输入图像描述


推荐阅读