我可以使用带有pandas数据帧的散点图来绘制回归线并显示参数吗?

Mar*_*s W 11 python regression scatter-plot pandas

我想使用以下代码从Pandas数据帧生成Scatterplot:

df.plot.scatter(x='one', y='two, title='Scatterplot') 
Run Code Online (Sandbox Code Playgroud)

是否有可以使用Statement发送的参数,因此它绘制了一个回归线并显示拟合的参数?

就像是:

df.plot.scatter(x='one', y='two', title='Scatterplot', Regression_line)
Run Code Online (Sandbox Code Playgroud)

Pas*_* dB 28

我不认为DataFrame.plot()有这样的参数.但是,您可以使用Seaborn轻松实现此目的.只需将pandas数据传递给lmplot(假设你安装了seaborn):

import seaborn as sns
sns.lmplot(x='one',y='two',data=df,fit_reg=True) 
Run Code Online (Sandbox Code Playgroud)

  • 伟大的!这个对我有用。您知道如何在图表上绘制回归参数吗? (2认同)
  • 不幸的是,这似乎不可能使用[问题](http://stackoverflow.com/questions/22852244/how-to-get-the-numerical-fitting-results-when-plotting-a-中发布的 lmplot Seaborn 中的回归)。但是,您可以在 [github](https://github.com/mwaskom/seaborn/issues/207) 上查看此问题。 (2认同)
  • 有没有办法在 seaborn 或 lmplot 中获得回归线的斜率值? (2认同)

osp*_*der 7

您可以使用 sk-learn 获得结合散点图的回归线。

from sklearn.linear_model import LinearRegression
X = df.iloc[:, 1].values.reshape(-1, 1)  # iloc[:, 1] is the column of X
Y = df.iloc[:, 4].values.reshape(-1, 1)  # df.iloc[:, 4] is the column of Y
linear_regressor = LinearRegression()
linear_regressor.fit(X, Y)
Y_pred = linear_regressor.predict(X)

plt.scatter(X, Y)
plt.plot(X, Y_pred, color='red')
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明