R abline() equivalent in Python
Asked Answered
E

3

1

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
Edmea answered 8/2, 2018 at 9:52 Comment(0)
F
2

Try this:

plt.plot(Boston.lstat, fit_1.fittedvalues, 'r')
Fadein answered 8/2, 2018 at 10:18 Comment(1)
Thanks a lot for the helpEdmea
U
5

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

Undercharge answered 8/2, 2018 at 10:19 Comment(1)
Your answer worked too, but I gave the check to @P W because he answered firstEdmea
F
2

Try this:

plt.plot(Boston.lstat, fit_1.fittedvalues, 'r')
Fadein answered 8/2, 2018 at 10:18 Comment(1)
Thanks a lot for the helpEdmea
N
1

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, '--')
Nag answered 15/9, 2022 at 12:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.