Http://blog.sina.com.cn/s/blog_aed5bd1d0102vid7.html
1. Polynomial-fitting Example:
ImportMatplotlib.pyplot as PltImportNumPy as Npx= Np.arange (1, 17, 1) y= Np.array ([4.00, 6.40, 8.00, 8.80, 9.22, 9.50, 9.70, 9.86, 10.00, 10.20, 10.32, 10.42, 10.50, 10.55, 10.58, 10.60]) Z1= Np.polyfit (x, Y, 3)#fitting with 3-time polynomialP1 =np.poly1d (z1)Print(p1)#print Fit polynomial on screenYVALS=P1 (x)#You can also use Yvals=np.polyval (z1,x)Plot1=plt.plot (x, Y,'*', label='Original Values') Plot2=plt.plot (x, Yvals,'R', label='Polyfit Values') Plt.xlabel ('x Axis') Plt.ylabel ('Y Axis') plt.legend (Loc=4)#Specify the location of the legend, the reader can help its usePlt.title ('polyfitting') Plt.show () Plt.savefig ('P1.png')
2. Specifying function Fitting
#fitting using nonlinear least squares methodImportMatplotlib.pyplot as Plt fromScipy.optimizeImportCurve_fitImportNumPy as NP#to fit in exponential formx = Np.arange (1, 17, 1) y= Np.array ([4.00, 6.40, 8.00, 8.80, 9.22, 9.50, 9.70, 9.86, 10.00, 10.20, 10.32, 10.42, 10.50, 10.55, 10.58, 10.60])deffunc (x,a,b):returnA*np.exp (b/x) popt, Pcov=Curve_fit (func, x, y) a=POPT[0]#popt inside is a fitting factor, and the reader can help its usageB=popt[1]yvals=func (x,a,b) plot1=plt.plot (x, Y,'*', label='Original Values') Plot2=plt.plot (x, Yvals,'R', label='Curve_fit Values') Plt.xlabel ('x Axis') Plt.ylabel ('Y Axis') plt.legend (Loc=4)#Specify the location of the legend, the reader can help its usePlt.title ('Curve_fit') Plt.show () Plt.savefig ('P2.png')
Python curve fit