相信很多初学者和我一样,在利用matplotlib库画图的时候遇到过图例不能显示中文的问题。经过仔细探索(百度+谷歌),现分享一种简单便捷一劳永逸的方法。
import numpy as np
from scipy.optimize import leastsq
import pylab as pl
import matplotlib
def func(x,p):
a,k,theta = p
return a*np.sin(2*np.pi*k*x+theta)
def residuals(p,y,x):
return y - func(x,p)
x = np.linspace(0,-2*np.pi,100)
a = 10
k = 0.34
theta = np.pi/6
y0 = func(x,[a,k,theta])
y1 = y0 + 2*np.random.randn(len(x))
p0 = [7,0.2,0]
plsq = leastsq(residuals,p0,args=(y1,x))
print('真实的参数',[a,k,theta])
print('拟合参数',plsq[0])
pl.plot(x,y0,label = '真实数据')
pl.plot(x,y1,label = '带噪声的实验数据')
pl.plot(x,func(x,plsq[0]),label = '拟合数据')
pl.legend()
pl.show()
运行之后,图例不能正常显示,只是几个框框。
#在前面加上下面三行:
from pylab import *
mpl.rcParams['font.sans-serif'] = ['SimHei']
mpl.rcParams['axes.unicode_minus'] = False
代码变成:
import numpy as np
from scipy.optimize import leastsq
import pylab as pl
import matplotlib
from pylab import *
mpl.rcParams['font.sans-serif'] = ['SimHei'] mpl.rcParams['axes.unicode_minus'] = False**
def func(x,p):
a,k,theta = p
return a*np.sin(2*np.pi*k*x+theta)
def residuals(p,y,x):
return y - func(x,p)
x = np.linspace(0,-2*np.pi,100)
a = 10
k = 0.34
theta = np.pi/6
y0 = func(x,[a,k,theta])
y1 = y0 + 2*np.random.randn(len(x))
p0 = [7,0.2,0]
plsq = leastsq(residuals,p0,args=(y1,x))
print('真实的参数',[a,k,theta])
print('拟合参数',plsq[0])
pl.plot(x,y0,label = '真实数据')
pl.plot(x,y1,label = '带噪声的实验数据')
pl.plot(x,func(x,plsq[0]),label = '拟合数据')
pl.legend()
pl.show()
运行该代码:
这样就轻松的解决了matplotlib中图例不能是中文的问题!