0%

linux环境中matplotlib画图缺少字体

本文主要解决linux环境下画图没中文字体的问题

问题描述

倘若使用的linux没有x协议支持,无法使用plt.show函数绘图,转而使用plt.savefigplt.close函数保存图片查看。我们使用以下代码添加中文支持。

补充: feh可以查看png图片,apt-get install fet安装它,feh example.png查看图片。

1
2
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus'] = False

但会出现下面报错

解决方法

字体下载安装

将字体放到对应文件夹

1
sudo cp SimHei.ttf /usr/share/fonts/SimHei.ttf

赋予使用权限

1
sudo chmod 777 /usr/share/fonts

配置matplotlib

方法1.删除缓存

已尝试,有效

查看matplotlib的缓存

1
2
3
4
import matplotlib as mlt

print(mlt.get_cacahedir())
# /home/ubuntu22/.cache/matplotlib

删除缓存

1
rm -rf /home/ubuntu22/.cache/matplotlib 

方法2.在matplotlib对应字体文件夹下更改

查看matplotlib配置文件位置

1
2
3
4
import matplotlib

print(matplotlib.matplotlib_fname())
# /home/ubuntu22/henu/ML/ml/lib/python3.10/site-packages/matplotlib/mpl-data/matplotlibrc

由输出,我们得到字体目录为

1
/home/ubuntu22/henu/ML/ml/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf

我们把安装好的字体复制过去一份

1
cp /usr/share/fonts/SimHei.ttf /home/ubuntu22/henu/ML/ml/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/SimHei.ttf