python - 如何根据目标变量的预测使用 Seaborn 绘制线性回归?

标签 python regression seaborn linear-regression regplot

我正在学习数据科学的基础知识,并从回归分析开始。因此,我决定构建一个线性回归模型来检查两个变量(chemical_1chemical_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);

enter image description here

最佳答案

使用子图并设置轴将允许您覆盖预测的 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/

相关文章:

python - 如何更改seaborn FacetGrid对象中的箱线图大小

Python 对相同的文本文件返回不同的结果

python - 在 OpenCV python 中打开未压缩的 TIFF 文件

Python seaborn facetGrid : Is it possible to set row category label location to the left

c++ - 如何使用 dlib 进行神经网络回归?

machine-learning - 一元词和二元词 (tf-idf) 不如二元词 (ff-idf) 准确?

python - seaborn 线图设置标记的透明度

python - 尝试在 Windows 上安装 pyodbc 时出现 "Microsoft Visual C++ … is required"错误

python - 如何在 pygame 中为我的角色添加加速?

python-3.x - fit_intercept 参数如何通过 scikit learn 影响线性回归