修改matplotlibrc文件 (永久解决方案)

  1. 定位matplotlibrc文件
    该文件位于[python_install_dir]\Lib\site-packages\matplotlib\mpl-data目录下。

  2. 修改matplotlibrc文件内容
    matplotlibrc文件部分内容如下:

1
2
3
4
5
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 文件部分内容如下所示:
1
2
3
4
5
6
7
8
9
10
S'Microsoft YaHei
p147
sg16
I700
sg17
g13
sg18
g13
sg19
S'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\ 目录下
  1. 重建字体索引列表
    matplotlib不会每次启动时都重新扫描所有的字体文件并创建字体索引列表,因此在复制完字体文件之后,需要运行下面的语句以重新创建字体索引列表 ,需要在console中运行以下代码:

    from matplotlib.font_manager import _rebuild
    _rebuild()

在py文件中显式加载字体 (临时解决方案)

  1. 显示加载matplotlib的字体管理器,代码如下:
1
2
3
4
5
6
7
8
9
# 加载自定义字体
# fname 为字体文件路径
import matplotlib
myfont = matplotlib.font_manager.FontProperties(fname=r'C:/Windows/Fonts/msyh.ttf')
...
# 在需要显示汉字的地方,指定自定义字体即可
plt.xlabel(u'汉字', fontproperties=myfont)
plt.xlabel(u'汉字', fontproperties=myfont)
...

参考文献

  1. matplotlib fast plot