简单记录一下matplotlib显示中文乱码的问题,参考了这篇博客。解决方法有两种,其中方法一成功了,第二种还是有点问题。。。

方法一

首先,查看已经安装的中文字体,如下

1
2
3
4
5
6
7
8
$ fc-list :lang=zh
/usr/share/fonts/opentype/noto/NotoSerifCJK-Regular.ttc: Noto Serif CJK TC:style=Regular
/usr/share/fonts/WinFonts/STXINGKA.TTF: STXingkai,华文行楷:style=Regular
/usr/share/fonts/WinFonts/STCAIYUN.TTF: STCaiyun,华文彩云:style=Regular
/usr/share/fonts/opentype/noto/NotoSerifCJK-Regular.ttc: Noto Serif CJK JP:style=Regular
/usr/share/fonts/opentype/noto/NotoSerifCJK-Regular.ttc: Noto Serif CJK KR:style=Regular
/usr/share/fonts/X11/misc/wenquanyi_10pt.pcf: WenQuanYi Bitmap Song:style=Regular
/usr/share/fonts/WinFonts/msjhl.ttc: Microsoft JhengHei,微軟正黑體,微軟正黑體 Light,Microsoft JhengHei Light:style=Light,Regular

这里我从Windows下复制了一些字体过来,安装方法比较简答,可以去Google一下。。。

查看字体以后,便可以通过设置FongProperties来实例化用于pyplot显示的字体,这里我选择了微软雅黑。后续在应用时,给出现中文的方法提供fontproperties值,便可以正常显示中文了。当然,其他的罗马字母的字体也会被修改。

1
2
3
4
from matplotlib.font_manager import *
myfont = FontProperties(fname='/usr/share/fonts/WinFonts/msyhbd.ttc')
...
plt.title("中文",fontproperties=myfont)

方法二

第二种方法是将中文字体添加到matplotlib的font中,根据安装位置的不同,可能出现在如下两个位置

  1. /usr/share/matplotlib/mpl-data/fonts
  2. ~/.local/lib/python3.6/site-packages/matplotlib/mpl-data/fonts

将字体文件复制到该路径下,并将字体名添加到matplotlibrc文件的sans-serif行,如下所示

1
#font.sans-serif: Microsoft YaHei, DejaVu Sans, Bitstream Vera Sans, Computer Modern Sans Serif, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif

最后,在应用时,设定rcParams[‘font.sans-serif’]为Microsoft Yahei

1
2
plt.rcParams['font.sans-serif'] = ['Microsoft Yahei']
plt.rcParams['font.family']='sans-serif'

References