解决 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()

相关推荐
风逸hhh1 小时前
python打卡day46@浙大疏锦行
开发语言·python
火兮明兮1 小时前
Python训练第四十三天
开发语言·python
互联网杂货铺2 小时前
完美搭建appium自动化环境
自动化测试·软件测试·python·测试工具·职场和发展·appium·测试用例
Gyoku Mint3 小时前
机器学习×第二卷:概念下篇——她不再只是模仿,而是开始决定怎么靠近你
人工智能·python·算法·机器学习·pandas·ai编程·matplotlib
莱茵菜苗3 小时前
Python打卡训练营day46——2025.06.06
开发语言·python
爱学习的小道长3 小时前
Python 构建法律DeepSeek RAG
开发语言·python
luojiaao4 小时前
【Python工具开发】k3q_arxml 简单但是非常好用的arxml编辑器,可以称为arxml杀手包
开发语言·python·编辑器
英英_4 小时前
视频爬虫的Python库
开发语言·python·音视频
猛犸MAMMOTH4 小时前
Python打卡第46天
开发语言·python·机器学习
多多*4 小时前
微服务网关SpringCloudGateway+SaToken鉴权
linux·开发语言·redis·python·sql·log4j·bootstrap