在 Linux 环境下解决 matplotlib
绘图中文显示异常(乱码/方框)的问题,可通过以下步骤配置中文字体支持:
完整解决方案
1. 安装中文字体(以 SimHei 为例)
bash
# 下载 SimHei 字体到系统字体目录
sudo wget -O /usr/share/fonts/SimHei.ttf https://zihao-openmmlab.obs.cn-east-3.myhuaweicloud.com/20220716-mmclassification/dataset/SimHei.ttf
# 更新字体缓存
sudo fc-cache -fv
2. 修改 matplotlib
配置文件
bash
# 定位 matplotlib 配置文件路径(通常在以下位置)
python -c "import matplotlib; print(matplotlib.matplotlib_fname())"
# 编辑配置文件(例如路径为 ~/.config/matplotlib/matplotlibrc)
nano ~/.config/matplotlib/matplotlibrc
在配置文件中修改或添加以下参数:
ini
font.family : sans-serif
font.sans-serif : SimHei, DejaVu Sans, Bitstream Vera Sans, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif
axes.unicode_minus : False # 解决负号显示异常
3. 清除 matplotlib 缓存
bash
rm -rf ~/.cache/matplotlib
4. 代码中显式指定字体(推荐)
python
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] # 指定默认字体
plt.rcParams['axes.unicode_minus'] = False # 解决负号显示问题
# 测试绘图
plt.plot([1, 2, 3], [4, 5, 6])
plt.title("中文标题测试")
plt.xlabel("X轴")
plt.ylabel("Y轴")
plt.show()
验证是否成功
bash
# 检查 matplotlib 可用字体列表是否包含 SimHei
python -c "from matplotlib.font_manager import FontManager; print([f.name for f in FontManager().ttflist if 'SimHei' in f.name])"
若输出包含 SimHei
,则配置成功。
常见问题排查
-
字体路径错误
- 确保字体文件已正确复制到
/usr/share/fonts/
或~/.fonts/
目录。 - 执行
fc-list | grep SimHei
检查字体是否被系统识别。
- 确保字体文件已正确复制到
-
缓存未更新
- 删除
~/.cache/matplotlib
并重启 Python 进程。
- 删除
-
代码冲突
- 避免在代码中重复设置
font.sans-serif
或在局部使用fontproperties
参数覆盖全局配置。
- 避免在代码中重复设置
通过以上步骤,可彻底解决 Linux 下 matplotlib
中文显示问题。若需其他字体(如宋体、楷体),方法同理,只需替换对应的字体文件即可。