使用 Matplotlib 或者 Seaborn 画图时,如果图像上需要显示中文,经常会发现出来的是一堆乱码(一般是方框),并且报以下的警告:
RuntimeWarning: Glyph 33891 missing from current font.
1. 安装系统依赖
如果系统并没有 fc-list 命令,则先需要安装下面的软件:
$ sudo yum install -y fontconfig mkfontscale ttmkfdir
安装完之后,查看下系统上支持的中文字体有哪些:
$ fc-list :lang=zh
2. 安装中文字体
这里我们会安装两个中文字体,分别是 SimHei(黑体) 和 Microsoft YaHei(微软雅黑),这两个字体可以在 Windows 系统的电脑上 C:\Windows\Fonts 中找到,当然你也可以这里进行下载 SimHei 字体。
将这两个字体上传到服务器 /usr/share/fonts/chinese 文件夹下(如果没有就创建一个文件夹),并改变相关权限:
$ sudo chmod -R 755 /usr/share/fonts/chinese$ sudo ttmkfdir -e /usr/share/X11/fonts/encodings/encodings.dir
修改 /etc/fonts/fiont.conf
<!-- Font directory list --><dir>/usr/share/fonts</dir><dir>/usr/share/X11/fonts/Type1</dir><dir>/usr/share/X11/fonts/TTF</dir><dir>/usr/local/share/fonts</dir><dir prefix="xdg">fonts</dir><dir>/usr/share/fonts/chinese</dir> <!--⭐--><!-- the following element will be removed in the future --><dir>~/.fonts</dir>
刷线一下缓存,并再次查看中文字体:
$ fc-cache$ fc-list :lang=zh/usr/share/fonts/chinese/MSYH.TTC: Microsoft YaHei:style=Normal/usr/share/fonts/chinese/SIMSUN.TTC: SimSun,宋体:style=Regular,常规/usr/share/fonts/chinese/MSYHBD.TTC: Microsoft YaHei:style=Έντονα/usr/share/fonts/chinese/MSYH.TTC: Microsoft YaHei UI:style=Normal/usr/share/fonts/chinese/MSYHBD.TTC: Microsoft YaHei UI:style=Έντονα/usr/share/fonts/chinese/SIMSUN.TTC: NSimSun,新宋体:style=Regular,常规/usr/share/fonts/chinese/MSYHL.TTC: Microsoft YaHei UI,Microsoft YaHei UI Light:style=Light,Regular/usr/share/fonts/chinese/SimHei.ttf: SimHei:style=Regular/usr/share/fonts/chinese/MSYHL.TTC: Microsoft YaHei,Microsoft YaHei Light:style=Light,Regular
3. Matplotlib配置
修改你 Python 环境下 site-packages/matplotlib/mpl-data/matplotlibrc 分别删除 249 行、257 行和 400 行前面的#号取消注释:
font.family : sans-seriffont.sans-serif : SimHei, Microsoft YaHei, Bitstream Vera Sans, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif,WenQuanYi Zen Hei Monoaxes.unicode_minus : False
注意:
font.sans-serif前面需要添加SimHei, Microsoft YaHei
删除 matplotlib 缓冲目录,并重新加载字体:
$ rm -rf ~/.cache/matplotlib$ python>>> from matplotlib.font_manager import _rebuild>>> _rebuild()
