You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Matplotlib字体无法更改求助:多种设置方法均无效

解决Matplotlib无法更换字体的问题

问题根源分析

  • 你通过matplotlib.font_manager.findSystemFonts()查不到Times New Roman,说明系统未安装该字体,Matplotlib自然无法调用;
  • 首次使用NotoSerifHebrew-Regular出现警告后无提示,是因为Matplotlib会缓存字体查找结果,后续直接使用fallback字体不再触发警告。

解决步骤

1. 安装目标字体并验证

  • 若系统无Times New Roman/Helvetica等字体,先手动安装:
    • Windows:一般默认自带,若缺失可从系统字体库找回或下载安装包;
    • macOS/Linux:通过系统字体管理工具或包管理器安装(如Linux用apt install fonts-dejavu或对应字体包);
  • 安装完成后,重新运行findSystemFonts(),确认能看到目标字体的文件路径。

2. 清除Matplotlib字体缓存

Matplotlib会缓存已识别的字体列表,新装字体不清除缓存无法被识别:

import matplotlib
print(matplotlib.get_cachedir())  # 输出缓存目录路径

手动删除该目录下的fontlist-v*.json文件,然后重启Python/Notebook,让Matplotlib重新生成字体缓存。

3. 正确指定字体的可靠方案

方案一:直接指定字体文件路径(最稳妥)

通过FontProperties加载字体文件,避免家族名识别错误:

from matplotlib import pyplot as plt
from matplotlib.font_manager import FontProperties

# 替换为你找到的目标字体文件路径
font_path = "/usr/share/fonts/truetype/times/TimesNewRoman.ttf"  # 示例路径
custom_font = FontProperties(fname=font_path)

# 应用到标题、坐标轴标签等
plt.title('Title', fontproperties=custom_font)
plt.xlabel('X Axis', fontproperties=custom_font)
plt.ylabel('Y Axis', fontproperties=custom_font)
plt.show()
方案二:通过字体家族名全局设置(需先验证家族名)

先获取字体的正确家族名,再全局配置:

from matplotlib import pyplot as plt
from matplotlib.font_manager import FontProperties

font_path = "/path/to/TimesNewRoman.ttf"
font_name = FontProperties(fname=font_path).get_name()  # 获取正确家族名

# 全局设置
plt.rcParams.update({
    "font.family": font_name,
    "axes.labelsize": 18,
    "axes.titlesize": 20,
    "legend.fontsize": 20,
    "xtick.labelsize": 28,
    "ytick.labelsize": 40
})

plt.title('Title')
plt.show()

4. 验证字体是否生效

运行以下代码确认当前使用的字体:

from matplotlib import pyplot as plt

plt.title('Test Font')
print("全局字体家族:", plt.rcParams["font.family"])
print("标题使用字体:", plt.gca().title.get_fontname())

内容的提问来源于stack exchange,提问作者PhysicsPerson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 03:20:27