python matplotlib fitting a straight line

 

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) # Cantilever # modify data. 1: the 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]) # Half-bridge # modify the data 2: an 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 (the X1, Yl) # generated line fit the plotted points _x1 = [0, 200 is ] _Y1 = [a0 + a1 * x for x in _X1] A0, A1 = linear_regression (an X2, Y2) # generates a fitted line of plotted points _X2 = [0, 200 is ] _Y2 = [a0 + a1 * x for x in _X1] # Display image plt.plot (the X1, Yl, ' RO ' , as linewidth = 2, label = " Wheatstone bridge " ) plt.plot (_x1, _y1, ' B ' , as linewidth = 2, label = ' Wheatstone bridge ' , Color = ' C0 ' ) plt.plot (an X2, Y2, ' G ^ ' , as linewidth = 2, label = ' half bridge ' ) plt.plot(_X2, _Y2, 'b', linewidth=2,label='半桥',color='C1') plt.xlabel('weight/g') plt.ylabel('voltage/v') plt.legend () plt.show()

 

Guess you like

Origin www.cnblogs.com/-wenli/p/11886483.html