python matplotlib擬合直線的實現

2022-10-04 15:48:22 字數 1434 閱讀 9528

**如下

import numpy as np

import huxjagkhwmatplotlib.pyplot as plt

plt.rcparams['font.family'] = ['sans-serif']

plt.rcparams['font.sans-serif'] = ['simhe']

def linear_regression(x, y):

n = len(x)

sumx = sum(x)

sumy = sum(y)

sumx2 = sum(x ** 2)

sumxy = sum(x * y)

a = np.mat([[n, sumx], [sumx, sumx2]])

b = np.array([sumy, sumxy])

return np.linalg.solve(a, b)

#單臂#修改資料1:

x1=np.array([0,20,40,60,80,100,120,140,160,180,200])

y1=np.array([0,0.02,0.06,0.1,0.13,0.16,0.19,0.22,0.245,0.278,0.3])

#半橋#修改資料2:

x2=np.array([0,20,40,60,80,100,120,140,160,180,200])

y2=np.array([0,0.057,0.118,0.185,0.245,0.308,0.376,0.425,0.488,0.544,0.58])

a0, a1 = linear_regression(x1, y1)

# 生成擬合直線的繪製點

_x1 = [0, 200]

_y1 = [a0 + a1 * x for x in _x1]

a0, a1 = linear_regression(x2, y2)

# 生成擬合直線的繪製點

_x2 = [0, 200]

_y2 = [a0 + a1 * x for x in _x1]

#顯示影象

plt.plot( x1, y1, 'ro', linewidth=2,label="單臂電橋")

plt.plot(_x1, _y1, 'b',linewidth=2,label='單臂電橋',color='c0')

plt.plot( x2, y2, 'g^', linewidth=2,label='半橋')

plt.plot(_x2, _y2, 'b', linewidth=2,label='半橋',co程式設計客棧lor='c1')

plt.xlab程式設計客棧el('weight/g')

plt.ylabel('voltage/v')

plt.legend()

plt.show()

圖例本文標題: python matplotlib擬合直線的實現

本文位址:

直線擬合 matlab基礎直線擬合

本文介紹利用矩陣除法進行最小二乘直線擬合 矩陣除法最小二乘直線擬合的函式檔案,參考matlab2018從入門到精通 中文版 function k,b linefit x,y n length x x reshape x,n,1 生成列向量 y reshape y,n,1 a x,ones n,1 b...

擬合專題 直線擬合

閒來無事,整理下擬合方面的一些方法 部分內容參考gloomyfish grooveboy等部落格,在此先行謝過 直線擬合方法主流方法有最小二乘 hough兩種,其他如halcon上的最小距離也是最小二乘的思想,其他如hough變換和最小二乘結合 混沌粒子群結合等等 1 最小二乘擬合直線 曲線擬合中最...

OpenCV直線擬合

摘抄自 opencv 提供的直線擬合函式。函式原型如下 void fitline inputarray points,outputarray line,int disttype,double param,double reps,double aeps disttype 指定擬合函式的型別,可以取 c...