MacOS 设置下 matplotlib 显示中文

MacOS 设置下 matplotlib 显示中文

  在网上尝试了N多方法,比如将字体文件复制到 matplotlibrc 目录,最后都会提示错误,基本快放弃了:

  warn_deprecated("2.2", "Passing one of 'on', 'true', 'off', 'false' as a "
//anaconda3/envs/tensorflow35/lib/python3.5/site-packages/matplotlib/font_manager.py:1238: UserWarning: findfont: Font family ['sans-serif'] not found. Falling back to DejaVu Sans.
  (prop.get_family(), self.defaultFamily[fontext]))

  
  显示结果如下图:
mshk.top
  
  最后尝试通过以下方法可以解决问题:
  1、通过 MacOS 的搜索,输入 font 打开字体册。
mshk.top
  
  2、找到你想要的字体,右键选择在访达中显示,我选择的是苹方-简-细体。再将字体从Finder拖到控制台,可以看到字体所在路径。
mshk.top
  
  3、进入到 matplotlib 缓存目录,看到有 fontlist 开头的文件,打开并编辑,我这里的文件名称是fontlist-v300.json

$ cd ~/.matplotlib
$ tree 
.
|____tex.cache
|____fontlist-v300.json

  
  4、在 fontlist-v300.json 中,找到 ttflist ,在下面增加以下内容,并保存。

...
    {
      "name": "PingFang",
      "stretch": "normal",
      "weight": 400,
      "__class__": "FontEntry",
      "variant": "normal",
      "style": "normal",
      "fname": "/System/Library/Fonts/PingFang.ttc",
      "size": "scalable"
    },
...

  
  5、自此已经完成修改,可以使用下面的 Python 代码,测试是否已经加载我们需要的字体。
  mshk.top.py:

import matplotlib.font_manager as fm
a=sorted([f.name for f in fm.fontManager.ttflist])  

for i in a:  
    print(i) 
$ python mshk.top.py | grep PingFang
PingFang

可以看到有我们设置的 PingFang 字体

  
  在项目中使用下面的代码引用:

from pylab import mpl  # 作图显示中文
mpl.rcParams['font.sans-serif'] = ['PingFang']  # 中文
mpl.rcParams['axes.unicode_minus'] = False   # 负号

  
  最后,测试 matplotlib 输出的结果显示的结果如下图:
mshk.top

  

  希望本文对您有帮助,感谢您的支持和阅读我的博客。
  


博文作者:迦壹
博客地址:MacOS 设置下 matplotlib 显示中文
转载声明:可以转载, 但必须以超链接形式标明文章原始出处和作者信息及版权声明,谢谢合作!


One thought on “MacOS 设置下 matplotlib 显示中文

回复 xy 取消回复

您的电子邮箱地址不会被公开。 必填项已用*标注