python添加趋势线

前两天做半导体激光泵浦实验,记录了一些数据,看起来像是直线,想用python拟合一下,翻看了帮助的文档,写了一些代码,在此由衷希望本科新生早早学会一门编程语言,虽然excel也能胜任,但编程能做到更多
主要用的numpy里面的函数是polyfit,这个函数有三个参量(x,y,n),x和y是要输入的数据,n是要进行要拟合的多项式的最高次数,比如此次用的就是线性拟合,n=1,其返回值是多项式拟合的系数,对于线性拟合就是斜率和截距,另外要调用的函数就是poly1d,拟合出这个多项式来,用polyfit的返回值作为参数。
代码如下

import matplotlib.pyplot as plt  
x1=[20,33,51,79,101,121,132,145,162,182,203,219,232,243,256,270,287,310,325]
y1=[49,48,48,48,48,87,106,123,155,191,233,261,278,284,297,307,341,319,341]
x2=[31,52,73,92,101,112,126,140,153,175,186,196,215,230,240,270,288,300]
y2=[48,48,48,48,49,89,162,237,302,378,443,472,522,597,628,661,690,702]
x3=[30,50,70,90,105,114,128,137,147,159,170,180,190,200,210,230,243,259,284,297,311]
y3=[48,48,48,48,66,173,351,472,586,712,804,899,994,1094,1198,1360,1458,1578,1734,1797,1892]
p1=np.poly1d(np.polyfit(x1[5:],y1[5:],1))
p2=np.poly1d(np.polyfit(x2[5:],y2[5:],1))
p3=np.poly1d(np.polyfit(x3[5:],y3[5:],1))
x=np.arange(20,350)
l1=plt.plot(x,p1(x),'r--',label='532nm')
l2=plt.plot(x,p2(x),'g--',label='offKDP')
l3=plt.plot(x,p3(x),'b--',label='offNd:VYO4')
plt.plot(x1,y1,'ro-',x2,y2,'g+-',x3,y3,'b^-')
plt.title('The Lasers in Three Conditions')
plt.xlabel('I/mA')
plt.ylabel('Power/uW')
plt.legend()
plt.show()```
![laser.png](http://upload-images.jianshu.io/upload_images/5994256-d83529989b68c8cc.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
参考自:https://docs.scipy.org/doc/numpy/reference/generated/numpy.polyfit.html

你可能感兴趣的:(python添加趋势线)