Matplotlib默认不显示中文,如果不设置,会出现小方块代替中文字符。为了在绘图中能正确显示中文, 可以有几种解决方案。
(1) 在程序中直接指定字体;
(2) 在程序开头修改配置字典 rcParams;
(3)修改配置文件。
下面代码实现了通过修改字体实现绘图中显示中文的问题。
from matplotlib.font_manager import FontProperties
import matplotlib. pyplot as plt
import numpy as np
font =FontProperties(fname="C:/Windows/Fonts/STXINGKA.TTF")
x = np.linspace(0,10,100)
y = x**2-2*x
plt.plot(x,y,label='$y=x^2-2x$')
plt.xlabel('横坐标',fontproperties=font)
plt.ylabel('纵坐标',fontproperties=font)
plt.title('标题',fontproperties=font)
plt.legend()
plt.show()
其中font =FontProperties(fname="C:/Windows/Fonts/STXINGKA.TTF")
是设置电脑中字体库中字体(STXINGKA
指的是华文行楷
)所在的位置。当然对于windows系统而言,简单在程序开头写上plt.rcParameter['font.fimily']=['SimHei']
可以设置微软雅黑字体。