散点图与直线拟合

import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib as mpl
import matplotlib.pyplot as plt
df1=pd.read_excel('E:/CW/CS.xlsx',sheetname=0)
df2=pd.read_excel('E:/CW/CS.xlsx',sheetname=1)
df3=pd.read_excel('E:/CW/CS.xlsx',sheetname=2)
df1_mat=df1[:24].as_matrix()
df2_mat=df2[:24].as_matrix()
df3_mat=df3[:24].as_matrix()
a=[]
b=[]
c=[]
for i in range(24):
    for j in range(9):
        a.append(df1_mat[i][j])
        b.append(df2_mat[i][j])
        c.append(df3_mat[i][j])
df1_dr=pd.read_excel('E:/CW/DR.xlsx',sheetname=0)
df2_dr=pd.read_excel('E:/CW/DR.xlsx',sheetname=1)
df3_dr=pd.read_excel('E:/CW/DR.xlsx',sheetname=2)
df1dr_mat=df1_dr[:24].as_matrix()
df2dr_mat=df2_dr[:24].as_matrix()
df3dr_mat=df3_dr[:24].as_matrix()
x=[]
y=[]
z=[]
for i in range(24):
    for j in range(9):
        x.append(df1dr_mat[i][j])
        y.append(df2dr_mat[i][j])
        z.append(df3dr_mat[i][j])
from sklearn import linear_model
LR1=linear_model.LinearRegression()
LR2=linear_model.LinearRegression()
LR3=linear_model.LinearRegression()
x1_array=np.array(x).reshape(-1, 1)#将数据转化成n行1列,对于只有一个特征时需要该操作
x2_array=np.array(y).reshape(-1, 1)
x3_array=np.array(z).reshape(-1, 1)
y1_array=np.array(a)
y2_array=np.array(b)
y3_array=np.array(c)
LR1.fit(x1_array,y1_array)
LR2.fit(x2_array,y2_array)
LR3.fit(x3_array,y3_array)
LinearRegression(copy_X=True, fit_intercept=True, n_jobs=1, normalize=False)
print(LR1.coef_,LR1.intercept_)
print(LR2.coef_,LR2.intercept_)
print(LR3.coef_,LR3.intercept_)
(array([ 1.75192196]), -275.48938146151511)
(array([ 1.69977594]), -264.25957272468219)
(array([ 1.64036973]), -251.8584170631708)

y1=1.7519x1-275.4893
y2=1.6997x2-264.2595
y3=1.6403x3-251.8584
真正的曲线为:y=1.6667x-258.3333

y1_predict=list(LR1.predict(x1_array))
y2_predict=list(LR2.predict(x2_array))
y3_predict=list(LR3.predict(x3_array))
x1_nihe=[x[0],x[8]]
y1_nihe=[y1_predict[0],y1_predict[8]]
x2_nihe=[y[0],y[8]]
y2_nihe=[y2_predict[0],y2_predict[8]]
x3_nihe=[z[0],z[8]]
y3_nihe=[y3_predict[0],y3_predict[8]]
plt.figure()  
plt.plot(x1_nihe,y1_nihe,'r')
plt.plot(x2_nihe,y2_nihe,'g')
plt.plot(x3_nihe,y3_nihe,'b')
plt.scatter(x=x,y=a,color='r',marker='^',label='t=20 Centigrade')
plt.scatter(x=y,y=b,color='g',marker='*',label='t=0 Centigrade')
plt.scatter(x=z,y=c,color='b',marker='.',label='t=-30 Centigrade')
plt.legend(loc=0)
plt.title('Humidity curve fitting diagram')
plt.xlabel('Capacity values')
plt.ylabel('Humidity')

plt.show()

散点图与直线拟合_第1张图片

你可能感兴趣的:(python)