2020-09-11
阅读量:
1010
在python中如何在做完最小二乘回归后画拟合图?
#导入相关库
import pandas as pd
import numpy as np
from sklearn import linear_model
import matplotlib as mpl
import matplotlib.pyplot as plt
#准备数据
x=np.array([1,2,3,4,5,6]).reshape(6,1)
y=np.array([2,3,5,7,9,12])
#实例化回归对象
reg=linear_model.LinearRegression()
#拟合回归对象
reg.fit(x,y)
#根据回归结果预测y值
y_predict = reg.predict(x) # 预测值
#画散点图及拟合图
#生成图纸fig,还有一个坐标系ax1
fig,ax1=plt.subplots()
#在坐标系上添加散点图
ax1.scatter(x.reshape(6),y)
#在坐标系上添加折线图
ax1.plot(x.reshape(6),y_predict,label="张三对应的回归线",color='r')
#设定一个常用的字体字号等属性,方便以后调用
prop1= mpl.font_manager.FontProperties(fname=r'C:\Windows\Fonts\msyh.TTF',size=10)
#添加图例
ax1.legend(loc=1,prop=prop1)






评论(0)


暂无数据
推荐帖子
0条评论
0条评论
0条评论