R abline() equivalent in Python

Question:

I am trying to plot a Linear Regression onto a scatterplot in Python.

In R I would simply do the following:

Run OLS Linear Regresion

fit_1 <- lm(medv ~ lstat)
plot(medv ~ lstat)
abline(fit_1, col = "red")

I have been looking at different solutions in Python, but I can’t seem to be able to actually get it to work.

My script is:

Plot Data

Boston.plot(kind='scatter', x='medv', y='lstat', color = "black")
plt.show()

Run Linear Regression

fit_1 = sm.ols(formula='medv ~ lstat', data= Boston).fit()

Show Summary

fit_1.summary()

Plot Regression Line

Insert code here

Asked By: ShieldData

||

Answers:

Try this:

plt.plot(Boston.lstat, fit_1.fittedvalues, 'r')
Answered By: PaW

It can be done quite simply. In the below code, I use sklearn to fit the model and predict the values.

import pandas as pd
from sklearn.linear_model import LinearRegression
from matplotlib import pyplot as plt

model = LinearRegression()
model.fit(X,y)
predictions = model.predict(X)

plt.plot(X,y,'o')
# change here
plt.plot(X, predictions, '-')
plt.show()

enter image description here

Answered By: Clock Slave

Saw this on Statology that helped me a lot:

def abline(slope, intercept):
     axes = plt.gca()
     x_vals = np.array(axes.get_xlim())
     y_vals = intercept + slope * x_vals
     plt.plot(x_vals, y_vals, '--')
Answered By: Krousties
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.