代码参考:
#--coding:utf-8--
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import linear_model
def getdata(filename):
data = pd.read_excel(filename, encoding="utf-8",sheet_name="Sheet1")
# 把pandas dataframe对象或series对象转换成list
# x = data["x"].tolist()
# y = data["y"].tolist()
x=np.asarray(data["x"])
y=np.asarray(data["y"])
return x,y
x,y=getdata("E:\\jupyterspace\\26_fields_fewerdata.xlsx")
#生成散点图
# plt.scatter(x,y)
# plt.show()
#生成一元线性回归图
def show_linear_line(x1,y1):
#使用sklearn报错ValueError: Expected 2D array, got 1D array instead
x1=x1.reshape(-1, 1)
y1=y1.reshape(-1, 1)
regr = linear_model.LinearRegression().fit(x1,y1)
plt.scatter(x1,y1,color="blue",linewidth=5)
plt.plot(x1,regr.predict(x1),color="red",linewidth=2)
plt.xticks();
plt.yticks();
plt.show()
show_linear_line(x,y)