25

I would like to produce a Scatterplot from a Pandas dataframe using the following code:

df.plot.scatter(x='one', y='two, title='Scatterplot') 

Is there a Parameter I can send with the Statement, so it plots a Regression line and shows the Parameters of the fit?

something like:

df.plot.scatter(x='one', y='two', title='Scatterplot', Regression_line)
Markus W
  • 1,451
  • 5
  • 19
  • 32

2 Answers2

52

I don't think that there's such a paramter for DataFrame.plot(). However, you can easily achieve this using Seaborn. Just pass the pandas dataframe to lmplot (assuming you have seaborn installed):

import seaborn as sns
sns.lmplot(x='one',y='two',data=df,fit_reg=True) 
Pascal dB
  • 536
  • 5
  • 4
  • 2
    great! it works for me. Do you know how I can plot the Regression parameters on the Chart? – Markus W Apr 05 '16 at 10:05
  • 2
    Unfortunately, this seems to be not possible using lmplot as posted in this [question](http://stackoverflow.com/questions/22852244/how-to-get-the-numerical-fitting-results-when-plotting-a-regression-in-seaborn). However, you may have a look at this issue on [github](https://github.com/mwaskom/seaborn/issues/207). – Pascal dB Apr 05 '16 at 10:48
  • Thanks a lot for your help. – Markus W Apr 05 '16 at 11:08
  • 3
    is there a way in seaborn or lmplot where I could get the slope value of the regression line? – Hana Feb 19 '18 at 19:03
  • @PascaldB, very elegant! – rohit_wason Feb 21 '19 at 14:59
  • Works like a charm. however, I have to set df.columns first, since x and y only accepts string. – ospider Sep 03 '20 at 03:06
18

You can use sk-learn to get the regression line combined with scatter plot.

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()

enter image description here

ospider
  • 9,334
  • 3
  • 46
  • 46