最近发现MacOS使用Matplotlib的时候中文显示乱码,只需要花1分钟配置一下,可以解决这个问题。

第一步,查看python的路径

1
2
$ type python
python is /usr/local/anaconda3/envs/py27/bin/python

提示:我这里边使用的是anaconda来管理多个Python版本信息

第二步,拷贝SimHei.ttf至指定目录,及配置matplotlibrc文件

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
$ cd /usr/local/anaconda3/envs/py27/lib/python2.7/site-packages/matplotlib/mpl-data/fonts/ttf

$ cp ~/Downloads/simhei.ttf  SimHei.ttf

$ cd ../..

$ tree 
├── fonts/
├── images/
├── stylelib/
└── matplotlibrc

vim matplotlibrc在最后添加上

font.family         : sans-serif
font.sans-serif     : SimHei
axes.unicode_minus  : False

第三步,删除缓存的ttf

1
2
rm -rf ~/.matplotlib/*.cache
rm ~/.matplotlib/fontList.json // 必须执行这一行,否则不生效

最后运行一下,发现问题解决了。

参考链接:

  1. 彻底解决matplotlib中文乱码问题
  2. matplotlib font not found
  3. 黑体字体simhei.ttf