【问题标题】:How to plot linear regression with Seaborn based on a prediction of a target variable?如何根据目标变量的预测使用 Seaborn 绘制线性回归?
【发布时间】:2018-09-24 18:48:00
【问题描述】:

我正在学习数据科学的基础知识,并从回归分析开始。所以我决定建立一个线性回归模型来检查这个dataset中的两个变量(chemical_1chemical_2)之间的线性关系。

我将chemical_1 设为预测变量(自变量),将chemical_2 设为目标(因变量)。然后使用scipy.stats.linregress 计算回归线。

from scipy import stats

X = df['chemical_1']
Y = df['chemical_2']

slope, intercept, r_value, p_value, slope_std_error = stats.linregress(X,Y)
predict_y = slope * X + intercept

我想出了如何用 matplotlib 绘制回归线。

plt.plot(X, Y, 'o')
plt.plot(X, predict_y)
plt.show()

但是我想用 Seaborn 绘制回归图。我目前发现的唯一选择如下:

sns.set(color_codes=True)
sns.set(rc={'figure.figsize':(7, 7)})
sns.regplot(x=X, y=Y);

有没有办法为 Seaborn 提供回归线 predict_y = slope * X + intercept 以构建回归图?

UPD:当使用 RPyStats 提出的以下解决方案时,Y 轴将获得 chemical_1 名称,尽管它应该是 chemical_2

fig, ax = plt.subplots()
sns.set(color_codes=True)
sns.set(rc={'figure.figsize':(8, 8)})
ax = sns.regplot(x=X, y=Y, line_kws={'label':'$y=%3.7s*x+%3.7s$'%(slope, intercept)});
ax.legend()
sns.regplot(x=X, y=Y, fit_reg=False, ax=ax);
sns.regplot(x=X, y=predict_y,scatter=False, ax=ax);

【问题讨论】:

    标签: python plot regression linear-regression seaborn


    【解决方案1】:

    使用子图和设置轴将允许您覆盖预测的 Y 值。这能回答你的问题吗?

    print(predict_y.name)
    predict_y = predict_y.rename('chemical_2')
    fig, ax = plt.subplots()
    sns.set(color_codes=True)
    sns.set(rc={'figure.figsize':(7, 7)})
    sns.regplot(x=X, y=Y, fit_reg=False, ax=ax,scatter_kws={"color": "green"});
    sns.regplot(x=X, y=predict_y,scatter=False, ax=ax, scatter_kws={"color": "green"});
    

    【讨论】:

    • 更新了我的问题,你能看一下吗?你也能说出为什么情节有不同的颜色,而不仅仅是像往常一样的蓝色吗?是因为叠加吗?
    • 你的正确之处在于覆盖图会产生不同的颜色,将额外的参数传递给 sns.regplot 可以将它们设置为相同的颜色。 Y 轴名称被第二次调用 sns.regplot 覆盖。它显示“chemical_1”,因为这是系列 predict_y 的名称。我可以在上面更新我的解决方案。
    • 知道了,谢谢!还有一个问题:您认为我是否正确添加了图例?它看起来符合预期,但我想知道 - 这是最优化的方式还是可以改进?
    • 您的最后一个问题是它在哪里变得主观,如果您对它感到满意并且它按预期工作,那么保持原样可能是安全的。另外,我还没有做太多关于在 seaborn 情节中添加图例的研究。
    猜你喜欢
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 2017-03-29
    • 2011-12-20
    • 1970-01-01
    • 2021-02-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多