Python matplotlib 成功使用SimHei 中文字体
1. 背景
Python 使用 matplotlib 库 设置中文字体时
plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False
出现下面的错误:
UserWarning: Glyph 25968 (\N{CJK UNIFIED IDEOGRAPH-6570}) missing from font(s) DejaVu Sans.plt.tight_layout()
findfont: Generic family 'sans-serif' not found because none of the following families were found: SimHei
findfont: Generic family 'sans-serif' not found because none of the following families were found: SimHei
findfont: Generic family 'sans-serif' not found because none of the following families were found: SimHei
findfont: Generic family 'sans-serif' not found because none of the following families were found: SimHei
findfont: Generic family 'sans-serif' not found because none of the following families were found: SimHei
findfont: Generic family 'sans-serif' not found because none of the following families were found: SimHei
报错信息表明在绘制图形时,系统缺少所需的字体(如SimHei),导致无法正确显示中文字符
2. 下载
下载地址:
https://gitcode.com/open-source-toolkit/c55ef/?utm_source=tools_gitcode&index=top&type=card
下载后更名
sudo mv Ubuntu_18.04_SimHei.ttf SimHei.ttf
3. 更新
3.1 将下载的SimHei.ttf文件移动到系统的字体目录中
sudo mv SimHei.ttf /usr/share/fonts/truetype/
3.2 更新系统的字体缓存
sudo fc-cache -fv
3.3 查看系统中的字体
$ fc-list | grep "SimHei"
/usr/share/fonts/truetype/SimHei.ttf: SimHei,黑体:style=Regular
3.4 清理 matplotlib 缓存目录
rm ~/.cache/matplotlib -fr
3.5 重新启动IDE运行代码
生成图片如下
4. 参考
Matplotlib 找不到基本字体