解决 Matplotlib 中文乱码的详细教程

解决 Matplotlib 中文乱码的详细教程

在使用 Matplotlib 进行数据可视化时,您可能会遇到中文字符显示为乱码或方块的问题。这通常是由于系统中未正确配置中文字体。以下是一个完整的教程,帮助您解决这个问题。


步骤 1:检查 Matplotlib 使用的配置文件路径

在 Jupyter Notebook 或 Python 环境中运行以下代码:

python 复制代码
import matplotlib
print(matplotlib.matplotlib_fname())

输出的路径是 Matplotlib 的配置文件 matplotlibrc 所在位置。这一步非常重要,尤其是在您的系统中存在多个 Python 环境(如 Anaconda 和系统自带 Python 环境)时。

例如,输出可能为:

复制代码
/home/xx/.local/lib/python3.13/site-packages/matplotlib/mpl-data/matplotlibrc

步骤 2:进入 Matplotlib 配置目录

根据上一步输出的路径,在终端中进入该目录:

bash 复制代码
cd /home/xx/.local/lib/python3.13/site-packages/matplotlib/mpl-data/

步骤 3:安装 SimHei 黑体字体

为了确保中文字符能正常显示,您需要将支持中文的字体(如 SimHei)导入到系统中。

下载 SimHei 字体

可以从以下链接下载 SimHei 字体(黑体):
SimHei 字体下载 - CSDN博客

将字体拷贝到 Matplotlib 字体目录

下载完成后,将 SimHei.ttf 复制到 Matplotlib 的字体目录。通常位于:

复制代码
/home/xx/.local/lib/python3.13/site-packages/matplotlib/mpl-data/fonts/ttf/

使用以下命令复制字体:

bash 复制代码
cp /path/to/SimHei.ttf /home/xx/.local/lib/python3.13/site-packages/matplotlib/mpl-data/fonts/ttf/

步骤 4:修改 Matplotlib 配置文件

使用文本编辑器(如 nanovim 或 VS Code)打开 matplotlibrc 文件:

bash 复制代码
nano /home/xx/.local/lib/python3.13/site-packages/matplotlib/mpl-data/matplotlibrc

找到以下部分:

text 复制代码
# font.family : sans-serif
# font.sans-serif : Bitstream Vera Sans, DejaVu Sans, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde

将这两行的注释去掉,并将 SimHei 添加为首选字体:

text 复制代码
font.family : sans-serif
font.sans-serif : SimHei, Bitstream Vera Sans, DejaVu Sans, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde

保存并退出编辑器(在 nano 中按 Ctrl + O 保存,Ctrl + X 退出)。


步骤 5:清除 Matplotlib 字体缓存

Matplotlib 会缓存字体信息,因此需要清除缓存以应用新字体。

  1. 查找缓存目录:

    python 复制代码
    import matplotlib
    print(matplotlib.get_cachedir())

    示例输出:

    复制代码
    /home/xx/.cache/matplotlib
  2. 删除缓存目录:

    bash 复制代码
    rm -rf /home/xx/.cache/matplotlib

步骤 6:测试中文显示

重新启动 Jupyter Notebook 或 Python 终端,运行以下代码,测试中文字体是否正常显示:

python 复制代码
import matplotlib.pyplot as plt

# 配置字体,确保中文正常显示
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

# 绘制简单图形
plt.plot([1, 2, 3], [4, 6, 5], label='测试图')
plt.title('中文显示测试')
plt.legend()
plt.show()

相关推荐
默_笙2 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
qq_426003962 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫2 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
长沙三为智能科技2 天前
家政小程序开发从0到上线:五阶段交付流程与验收清单
python
伞伞悦读2 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
只睡四小时2 天前
Canvas 弹道联机实战:700 行 + 固定时间步长
python·websocket·html5·游戏开发·canvas
奇思妙想聪明勤奋的小羊2 天前
DeepAgents第5章:子Agent 与上下文隔离—让 Agent学会委派
人工智能·python·学习·语言模型
lpfasd1232 天前
2026年第38周GitHub趋势周报
python·科技·github
IZero072 天前
Jev 与 Laya
python·语言模型