一、修改matplotlibrc文件 (永久解决方案)1. 定位matplotlibrc文件
该文件位于[python_install_dir]\Lib\site-packages\matplotlib\mpl-data目录下。
2. 修改matplotlibrc文件内容。
matplotlibrc文件部分内容如下:
font.family: sans-serif#默认情况下,该字段为关闭状态。去掉注释即可。font.sans-serif: Microsoft YaHei , Bitstream Vera Sans,Lucida Grande, Verdana, Geneva, Lucid,Arial, Helvetica, Avant Garde,sans-serif#添加”Microsoft YaHei”
在font.sans-serif中添加 Mircosoft YaHei 之后,matplot 通过 C:\Users\[your_account]\.matplotlib\fontList.cache 中存储的映射关系找到字体文件所在的位置。fontList.cache 文件部分内容如下所示:
S’Microsoft YaHeip147sg16I700sg17g13sg18g13sg19S’C:\\Windows\\Fonts\\msyhbd.ttf’
Microsoft YaHei字体默认的位置位于 C:\Windows\Fonts\ 目录下。
注意:如果第三步操作完之后仍不起作用,可以将 C:\Windows\Fonts\ 目录下的Microsoft YaHei字体文件拷贝到 [python_install_dir]\Lib\site-packages\matplotlib\mpl-data\fonts\ttf\ 目录下
3. 重建字体索引列表。
,需要在console中运行以下代码:
>>>from matplotlib.font_manager import _rebuild`>>>_rebuild()二、在py文件中显式加载字体 (临时解决方案)1. 显示加载matplotlib的字体管理器,代码如下: matplotlibmyfont = matplotlib.font_manager.FontProperties(fname=r’C:/Windows/Fonts/msyh.ttf’)…# 在需要显示汉字的地方,,指定自定义字体即可plt.xlabel(u’汉字’, fontproperties=myfont)plt.xlabel(u’汉字’, fontproperties=myfont)…
参考文献
人生就是一次充满未知的旅行,在乎的是沿途的风景,