使用matplotlib缺失中文字体的解决方案

出现问题

当我们用matplotlib作图时中文乱码,往往会发现中文的文字变成了小方块。

import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei'] 

尽管我们指定了中文字体。这时可能会因为系统中缺失中文字体而导致不能显示。具体表现就是,运行过程中报warning:

lib/python3.7/site-packages/matplotlib/font_manager.py:1241: UserWarning: findfont: Font family ['sans-serif'] not found. Falling back to DejaVu Sans.
  (prop.get_family(), self.defaultFamily[fontext]))

解决问题

1、首选安装、拷贝对应字体到系统中。比如这里我拷贝Windows系统中的黑体(simhei.ttf)到/usr/share/fonts/windows_fonts目录。

mkdir /usr/share/fonts/windows_fonts
sudo mv ~/simhei.ttf /usr/share/fonts/windows_fonts

接下来将目录中的字体注册到系统中,让系统能够识别到这些新字体。

cd /usr/share/fonts/windows_fonts
mkfontscale
mkfontdir
fc-cache

此时再用下面的命令查看已经安装好的字体:

fc-list  #列出系统识别到的已安装字体。

我们可以看到这么一条:

此时我们会发现matplotlib作出的图中中文依旧无法正常显示,这种情况只需删除matplotlib的缓存目录(~/.cache/matplotlib)即可解决。

rm -rf ~/.cache/matplotlib

至此中文就可以正常显示了。

作者書劍飄零
本文版权归作者和博客园所有,欢迎转载,但未经作者同意,必须保留此段声明,且在文章页面醒目位置显示原文连接,否则保留追究法律责任的权利。
原文地址:https://www.cnblogs.com/oboth-zl/p/15152508.html