Reputation: 125
I am trying to plot a Linear Regression onto a scatterplot in Python.
In R I would simply do the following:
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:
Boston.plot(kind='scatter', x='medv', y='lstat', color = "black")
plt.show()
fit_1 = sm.ols(formula='medv ~ lstat', data= Boston).fit()
fit_1.summary()
Upvotes: 1
Views: 8629
Reputation: 11
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, '--')
Upvotes: 1
Reputation: 7967
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()
Upvotes: 5