我正在学习数据科学的基础知识,并从回归分析开始。因此,我决定构建一个线性回归模型来检查两个变量(chemical_1
和 chemical_2
)之间的线性关系 dataset .
我将 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 =斜率* X +截距
以构建回归图?
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);
最佳答案
使用子图并设置轴将允许您覆盖预测的 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"});
关于python - 如何根据目标变量的预测使用 Seaborn 绘制线性回归?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49833426/