Matplotlib 中文乱码源于默认未加载中文字体,需手动指定 SimHei.ttf 路径并配置 font.family、font.sans-serif 和 axes.unicode_minus,同时重建字体缓存才能生效。

Matplotlib 中文乱码是因为默认没加载中文字体
Matplotlib 默认字体不支持中文,绘图时遇到 中文 就显示成方块或空格。这不是编码问题(utf-8 没错),也不是 plt.show() 的锅,而是字体列表里压根没有可用的中文字体路径。
手动指定 SimHei.ttf 路径最稳,别信自动搜索
Windows 自带的 SimHei.ttf 通常在 C:\Windows\Fonts\simhei.ttf,但 Matplotlib 不会自动扫描系统字体目录。靠 plt.rcParams['font.sans-serif'] = ['SimHei'] 往往失效——它只查内置字体名映射,而 SimHei 在多数 Matplotlib 版本中未预注册。
- 先确认文件存在:
import os; os.path.exists(r'C:\Windows\Fonts\simhei.ttf') - 用
FontProperties显式加载:from matplotlib.font_manager import FontProperties; simhei = FontProperties(fname=r'C:\Windows\Fonts\simhei.ttf') - 绘图时传入:
plt.title('标题', fontproperties=simhei)或plt.xlabel('横轴', fontproperties=simhei)
全局生效要改 rcParams,但必须配 font.family 和 fallback
想一劳永逸?可以改全局配置,但只设 font.sans-serif 不够,还得关掉 axes.unicode_minus(否则负号变方块),并指定 font.family 为 sans-serif。
让 macOS 自动化像说话一样简单 —— 用代码控制你的 Mac,无需学习 AppleScript 系统要求 macOS 14+ (Sonoma) Python 3.9+ 需要开启:辅助功能 + 屏幕录制权限
- 正确写法:
plt.rcParams['font.family'] = 'sans-serif' plt.rcParams['font.sans-serif'] = ['SimHei', 'Arial Unicode MS', 'DejaVu Sans'] plt.rcParams['axes.unicode_minus'] = False
- 注意顺序:
SimHei必须放在列表最前,否则可能被后项 fallback 掉 - Linux/macOS 用户不能直接用
SimHei,得换Noto Sans CJK SC或本地 ttf 路径
字体缓存不刷新会导致改了也不生效
Matplotlib 启动时会缓存字体列表,修改 rcParams 或复制新字体后,旧进程仍用旧缓存。不重启 Python 内核,plt.rcParams 的改动可能被忽略。
- 强制重建缓存:
import matplotlib as mpl; mpl.font_manager._rebuild() - 验证是否生效:
[f.name for f in mpl.font_manager.fontManager.ttflist if 'simhei' in f.name.lower()] - Jupyter 用户:执行完
_rebuild()后,必须重新运行绘图 cell,不能只改参数再 plt.show()
真正卡住人的往往不是配置本身,是缓存没清、路径写错斜杠、或者在非主线程里改 rcParams 却没同步到绘图上下文。
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!










