R abline() equivalent in Python

感情迁移 提交于 2019-12-13 10:29:43

问题


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

回答1:


Try this:

plt.plot(Boston.lstat, fit_1.fittedvalues, 'r')



回答2:


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



来源:https://stackoverflow.com/questions/48682407/r-abline-equivalent-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!