【问题标题】:How can I add an R^2 value to the legend of a seaborn barplot?如何将 R^2 值添加到 seaborn barplot 的图例中?
【发布时间】:2021-04-24 22:59:04
【问题描述】:

我有一个 seaborn 条形图和一条在其顶部绘制的回归线,看起来像 this。如您所见,我有一个使用 seaborn.barplot() 自动创建的图例,并且我正在尝试使用此添加 R^2 分数:

g = sns.barplot(x='City/Town', y="Value", hue="Metric", data=df, ax=ax1)
h, l = g.get_legend_handles_labels()
g.legend(h + [lin_reg.score(X, Y)], l + ['R^2 score'], title="Legend")

它不会抛出错误,事实上我知道它正在工作,因为它将标题更改为“Legend”,但它也没有添加 R^2。

【问题讨论】:

  • 什么是lin_reg.score(X, Y)
  • 您好,您的代码不完整。 X,Y 是什么?另一个情节在哪里,你的第二个轴,你用它做什么?你有示例数据集吗?和@Ynjxsjmh 一样的问题,lin_reg.score(X, Y) 是什么?

标签: python matplotlib seaborn


【解决方案1】:

legend() 函数在第一个参数中需要一个句柄,我认为您不能使用文本作为其中之一。你可以阅读更多help page for matplotlib legend

我能想到的一个快速解决方案是为用于 R^2 的行制作一个空白矩形,下面是一个以 iris 为例的示例:

import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
from sklearn.linear_model import LinearRegression 

df = sns.load_dataset("iris")
lin_reg = LinearRegression().fit(df[['petal_length']], df['sepal_length'])
r2 = lin_reg.score(df[['petal_length']], df['sepal_length'])

blank = Rectangle((0, 0), 1, 1, fc="w", fill=False, edgecolor='none', linewidth=0)

fig, ax = plt.subplots(figsize=(10,5))
sns.scatterplot(x='sepal_width', y="sepal_length", hue="species", data=df, ax=ax)

h, l = ax.get_legend_handles_labels()
ax.legend(h + [blank], l + [f'R^2 score = {r2:.3f}'], title="Legend")

我注意到您有一个包含几个类别的条形图,所以我不确定您如何从中计算 R^2。无论如何,使用上面的代码,您应该能够添加 R^2

【讨论】:

猜你喜欢
  • 2021-03-24
  • 2020-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-03
相关资源
最近更新 更多