python matplotlib拟合直线的实现

这篇文章主要介绍了python matplotlib拟合直线的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

代码如下

import numpy as np

import matplotlib.pyplot as plt

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

plt.rcParams['font.sans-serif'] = ['SimHei']

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='半桥',color='C1')

plt.xlabel('weight/g')

plt.ylabel('voltage/v')

plt.legend()

plt.show()

图例

以上是 python matplotlib拟合直线的实现 的全部内容, 来源链接: utcz.com/z/312308.html

回到顶部