matplotlib字体问题


报错findfont: Generic family ‘sans-serif’ not found because none of the following families were found: SimHei

报错信息表明 matplotlib 无法找到 SimHei 字体。可能的原因是字体没有正确安装或路径不正确,或者 matplotlib 的字体缓存未刷新。
解决方案
确认字体安装:确保 SimHei.ttf 已正确安装在系统的字体目录中。
手动配置 matplotlib 字体路径:将 SimHei.ttf 的具体路径添加到 matplotlib 的字体路径中。

1:手动安装并配置 SimHei 字体

下载 SimHei.ttf 字体
运行以下命令下载 SimHei 字体:

wget -O SimHei.ttf https://github.com/chinese-fonts/simhei/raw/master/SimHei.ttf

2.将字体文件复制到系统字体目录

将下载的字体文件复制到系统字体目录中:

sudo mkdir -p /usr/share/fonts/truetype/simhei
sudo cp SimHei.ttf /usr/share/fonts/truetype/simhei/

3.刷新字体缓存

执行以下命令来刷新字体缓存:

sudo fc-cache -fv

4.验证字体安装

检查字体是否正确安装:

fc-list | grep "SimHei"

如果看到了类似的输出,说明字体已经成功安装。

手动指定 matplotlib 使用的字体路径

如果问题仍然存在,可以手动将字体路径指定给 matplotlib

# 手动添加字体路径
font_path = '/usr/share/fonts/truetype/simhei/SimHei.ttf'
font_prop = fm.FontProperties(fname=font_path)

# 设置 Matplotlib 字体以支持中文
plt.rcParams['font.sans-serif'] = ['SimHei']  # 虽然指定了字体名,我们也需要使用FontProperties来确保字体加载
plt.rcParams['axes.unicode_minus'] = False  # 解决负号显示问题

文章作者: 你的朋友
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 你的朋友 !