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

相关推荐
深耕AI19 分钟前
【PyTorch训练】准确率计算(代码片段拆解)
人工智能·pytorch·python
eqwaak024 分钟前
科技信息差(9.12)
开发语言·python·科技·量子计算
Blossom.1181 小时前
从“能写”到“能干活”:大模型工具调用(Function-Calling)的工程化落地指南
数据库·人工智能·python·深度学习·机器学习·计算机视觉·oracle
蒋星熠1 小时前
破壁者指南:内网穿透技术的深度解构与实战方法
网络·数据库·redis·python·websocket·网络协议·udp
shizidushu1 小时前
使用 Pyinstaller 打包 PPOCRLabel
python·pyinstaller
Q_Q19632884752 小时前
python+springboot+uniapp微信小程序题库系统 在线答题 题目分类 错题本管理 学习记录查询系统
spring boot·python·django·uni-app·node.js·php
Rhys..2 小时前
.gitignore文件的作用及用法
python·github
IT学长编程2 小时前
计算机毕业设计 基于深度学习的酒店评论文本情感分析研究 Python毕业设计项目 Hadoop毕业设计选题 机器学习选题【附源码+文档报告+安装调试】
hadoop·python·深度学习·机器学习·数据分析·毕业设计·酒店评论文本情感分析
~-~%%3 小时前
Moe机制与pytorch实现
人工智能·pytorch·python