【问题标题】:How to annotate regression lines in seaborn lmplot?如何在 seaborn lmplot 中注释回归线?
【发布时间】:2019-06-20 07:20:34
【问题描述】:

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

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

 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"})

【问题讨论】:

  • 请阅读How to create a Minimal, Complete, and Verifiable example。此外,您提供的链接没有注释。它只是显示传奇。两者是有区别的
  • 我了解注释和显示图例之间存在差异。我对任何一个都持开放态度。我认为我的示例中的图例被占据了显示色调类别。我无法显示我拥有的数据(这是医疗保健数据)。我会尝试为 MWE 编造类似的数据。
  • 您可以使用 plt.legend 手动设置图例
  • 我更喜欢注释,正如问题标题所示。我可以在 matplotlib 中手动完成。我想知道通过 lmplot 或底层的 regplot 在 seaborn 中是否有更优雅的方式。说明书不清楚。 dir(*plot) 不清楚。
  • Seaborn 不允许您访问拟合参数。当使用色调时,它也不会让您访问各个行。最好使用 matplotlib 创建绘图,这样您就可以完全控制注释的内容和位置。

标签: python seaborn


【解决方案1】:

按原样使用您的代码:

 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 没有提供任何数据。

【讨论】:

    猜你喜欢
    • 2022-11-17
    • 2018-02-04
    • 1970-01-01
    • 1970-01-01
    • 2020-03-07
    • 2021-02-17
    • 1970-01-01
    • 2018-02-28
    • 2020-09-22
    相关资源
    最近更新 更多