is learning to do scientific computing with Python, and when practicing the least squares method, I encounter the problem that matplotlib cannot display Chinese. Check the information, feel the dynamic plus a few statements is the best, put all the code here.
#-*-Coding:utf-8-*-"" "Created on Wed 23:20:26 2016@author:administrator" "" Import NumPy as Npfrom Scipy.optimiz E import leastsqimport Pylab as PL "The way to display Chinese for matplotlib simply add the following three lines of code" ' Import matplotlib as mplmpl.rcparams[" Font.sans-serif "] = [" Microsoft yahei "]mpl.rcparams[' axes.unicode_minus '] = falsedef func (x, p): function A*sin required for data fitting ( K*np.pi*x + theta) ' A, K, theta = Preturn a*np.sin (2*k*np.pi*x + theta) def residuals (p, y, x): "' The difference between the experimental data and the fitted function, p is the parameter to fit the required ' ' Return (Y-func (x, p)) x = Np.linspace (0, -2*np.pi, +) A, k, theta = ten, 0.34, NP.PI/6 # The function parameters of the real data y0 = func (x, [A, K, the TA]) # real Data Y1 = y0 + 2 * NP.RANDOM.RANDN (len (x)) # Data after adding noise p0 = [7, 0.2, 0] # First guess function fitting function # Call LEASTSQ for data fitting # residuals The function for calculating the error # P0 is the initial value of the fitting parameter # args is the experimental data that needs to be fitted PLSQ = LEASTSQ (residuals, P0, args= (y1, x)) print ("True Parameters--", [A, K, Theta]) print ( "Fit Parameters--", plsq[0]) pl.plot (x, y0, label = "real Data") Pl.plot (x, y1, label = "Experimental data with Noise") Pl.plot (x, func (x, Plsq[0]), label = "Fit Data") Pl.legend () pl.show ()
Output Result:
Getting Started with Python data analysis Chinese display problem & least squares method for--matplotlib