Matplotlib绘图中文字符显示异常(方框、乱码)的解决方案

Matplotlib在默认情况下,99%的新环境(尤其是Linux、macOS、新装的Windows Conda、WSL)都会显示方框□□□或者乱码

平台 推荐方案(直接复制粘贴就行) 说明 成功率
Windows(原生) 什么都不用干! Windows 自带「微软雅黑」「SimHei」等,matplotlib 自动识别 100%
macOS 几乎也不用干 macOS 自带「PingFang SC」(苹果拼音),新版 matplotlib 自动用 99%
Linux / WSL / Jupyter / 云服务器 / Docker 必须手动设置!(下面3选1) 默认根本没有中文字体 ---

1. [最简单的写在最前] 懒人方案

(一行+几行,复制到代码最前面,所有环境都正常显示中文)

python 复制代码
import matplotlib.pyplot as plt
import matplotlib

# ===== 下面这 4 行放到你的代码最前面,通杀所有环境!=====
matplotlib.rcParams['font.sans-serif'] = ['SimHei']          # 黑体
matplotlib.rcParams['font.sans-serif'] = ['SimHei',            # 优先用黑体
                                          'SimSun',             # 备用:宋体
                                          'DejaVu Sans',        # 备用:英文
                                          'Arial Unicode MS',   # macOS 备用
                                          'PingFang SC']        # macOS 备用
matplotlib.rcParams['axes.unicode_minus'] = False              # 正常显示负号(重要!)

# 可选:如果你喜欢更现代的字体(更清晰漂亮)
# matplotlib.rcParams['font.sans-serif'] = ['Microsoft YaHei', 'SimHei', 'Arial Unicode MS', 'PingFang SC']
# ============================================================

放完这几行后,类似代码:

python 复制代码
plt.title("损失变化曲线")
plt.xlabel("训练轮数")
plt.ylabel("损失值")
plt.legend(["训练得到的直线", "真实直线"])

就会在 Windows / macOS / Linux / Jupyter Notebook / VS Code / Colab 全部完美显示中文,不会再出现方框等异常!

这种方法是在绘图代码中设置全局字体,实质是Python的Matplotlib包配置脚本中动态设置matplotlibrc,这样可以避免由于更改配置文件而造成的麻烦。

还可以更简单一些:

python 复制代码
import matplotlib
# 设置显示中文字体
matplotlib.rcParams["font.sans-serif"] = ["SimHei"]

有时候,字体更改后,会导致坐标轴中的部分字符无法正常显示,此时需要更改axes.unicode_minus参数:

python 复制代码
# 设置正常显示符号
matplotlib.rcParams["axes.unicode_minus"] = False

2. 更极致的方案(推荐给爱折腾的人)

2.1. 从网络上下载中文字体库

下载字体库SimHei.ttf(中文黑体)等中文字体库。

2.2. 使用以下命令查看Matplotlib使用的字体库配置文件路径和Matplotlib缓存路径

python 复制代码
import matplotlib
print("matplotlib字体配置文件: ", matplotlib.matplotlib_fname())
print("matplotlib字体缓存路径: ", matplotlib.get_cachedir())

结果例如:

bash 复制代码
(pytorch) moemoe@DESKTOP-MOEMOE:~$ python
Python 3.13.2 | packaged by Anaconda, Inc. | (main, Feb  6 2025, 18:56:02) [GCC 11.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import matplotlib
... print("matplotlib字体配置文件: ", matplotlib.matplotlib_fname())
... print("matplotlib字体缓存路径: ", matplotlib.get_cachedir())
... 
matplotlib字体配置文件:  /home/moemoe/miniconda3/envs/pytorch/lib/python3.13/site-packages/matplotlib/mpl-data/matplotlibrc
matplotlib字体缓存路径:  /home/moemoe/.cache/matplotlib
>>> 

2.3. 将下载到字体库复制到字体文件夹

以为matplotlib字体配置路径为例:

**/home/moemoe/miniconda3/envs/pytorch/lib/python3.13/site-packages/matplotlib/mpl-data/**matplotlibrc

那么,字体文件夹应该是以下目录

**/home/moemoe/miniconda3/envs/pytorch/lib/python3.13/site-packages/matplotlib/mpl-data/**fonts/ttf/

将从从网络上下载字体库复制到该目录:/home/moemoe/miniconda3/envs/pytorch/lib/python3.13/site-packages/matplotlib/mpl-data/fonts/ttf/

2.4. 修改Matplotlib配置文件matplotlibrc

例如此前matplotlib字体配置文件: /home/moemoe/miniconda3/envs/pytorch/lib/python3.13/site-packages/matplotlib/mpl-data/matplotlibrc

找到以下配置项并修改:

python 复制代码
# 取消注释并修改字体族配置
font.family         : sans-serif
 
# 取消注释并添加SimHei到字体列表开头
font.sans-serif     : SimHei, Bitstream Vera Sans, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif
 
# 解决负号显示问题
axes.unicode_minus  : False

一个实际的例子是:

python 复制代码
font.family:  sans-serif
#font.style:   normal
#font.variant: normal
#font.weight:  normal
#font.stretch: normal
#font.size:    10.0

#font.serif:  DejaVu Serif, Bitstream Vera Serif, Computer Modern Roman, New Century Schoolbook, Century Schoolbook L, Utopia, ITC Bookman, Bookman, Nimbus Roman No9 L, Times New Roman, Times, Palatino, Charter, serif
font.sans-serif: SimHei, Microsoft YaHei, SimSun, DejaVu Sans, Bitstream Vera Sans, Computer Modern Sans Serif, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif
#font.cursive:    Apple Chancery, Textile, Zapf Chancery, Sand, Script MT, Felipa, Comic Neue, Comic Sans MS, cursive
#font.fantasy:    Chicago, Charcoal, Impact, Western, xkcd script, fantasy
#font.monospace:  DejaVu Sans Mono, Bitstream Vera Sans Mono, Computer Modern Typewriter, Andale Mono, Nimbus Mono L, Courier New, Courier, Fixed, Terminal, monospace
......
#axes.spines.left:   True  # display axis spines
#axes.spines.bottom: True
#axes.spines.top:    True
#axes.spines.right:  True

axes.unicode_minus: False  # use Unicode for the minus symbol rather than hyphen.  See
                           # https://en.wikipedia.org/wiki/Plus_and_minus_signs#Character_codes

2.5. 清除Matplotlib字体缓存

python 复制代码
# 清除matplotlib字体缓存
rm -rf ~/.cache/matplotlib

其它

如果想用最美观的中文字体(推荐 2025 年流行的 3 款):

python 复制代码
# 方案A:思源黑体(最清晰、最现代,强烈推荐)
matplotlib.rcParams['font.sans-serif'] = ['Noto Sans SC', 'SimHei', 'PingFang SC']

# 方案B:阿里巴巴普惠体(超好看)
matplotlib.rcParams['font.sans-serif'] = ['Alibaba PuHuiTi', 'SimHei']

# 方案C:Windows 专属极致漂亮
matplotlib.rcParams['font.sans-serif'] = ['Microsoft YaHei', 'SimHei']

为避免不必要的麻烦,建议先下载字体文件放到系统字体文件夹:

  • Windows: C:\Windows\Fonts\
  • macOS: 双击安装
  • Linux: ~/.local/share/fonts/ 然后 fc-cache -fv
相关推荐
AI小云2 天前
【数据操作与可视化】Matplotlib绘图-生成其他图表类型
开发语言·python·matplotlib
咨询QQ276998852 天前
死区补偿量产方案 电机死区补偿算法,量产方案,可直接将算法模型移植到自己的实际项目模型中,算法...
matplotlib
Keep__Fighting3 天前
【机器学习:逻辑回归】
人工智能·python·算法·机器学习·逻辑回归·scikit-learn·matplotlib
jamin_liu_913 天前
Matplotlib安装、设置及绘图
matplotlib
咚咚王者4 天前
人工智能之数据分析 Matplotlib:第七章 项目实践
人工智能·数据分析·matplotlib
咚咚王者5 天前
人工智能之数据分析 Matplotlib:第一章 简介和安装
人工智能·数据分析·matplotlib
咚咚王者5 天前
人工智能之数据分析 Matplotlib:第五章 常见函数
人工智能·数据分析·matplotlib
咚咚王者5 天前
人工智能之数据分析 Matplotlib:第六章 知识总结
人工智能·数据分析·matplotlib
咚咚王者6 天前
人工智能之数据分析 Matplotlib:第四章 图形类型
人工智能·数据分析·matplotlib