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

相关推荐
郭老二3 小时前
【Python】基本语法:装饰器语法糖@
python
_Jimmy_4 小时前
Agent常用检索器的详细介绍
python·langchain
小柯南敲键盘4 小时前
图片翻译API接入与自动化实现指南
运维·python·自动化
旅僧4 小时前
Q-learning(自用)
python·机器学习
Python大数据分析@5 小时前
曝梁文锋称「一度不想维护C端用户,奈何赶不走」,DeepSeek真不需要C端用户吗?可能会有啥影响吗?
python
艾斯特_6 小时前
工作流与多Agent协作:LangGraph、MCP和A2A的应用分层
人工智能·python·ai
IT小盘6 小时前
04-大模型流式输出原理-SSE与Python实现
开发语言·网络·人工智能·python
我叫黑大帅6 小时前
add()和 __add__() 写法哪个更好呢?
后端·python·面试
不如语冰6 小时前
AI大模型入门-Python进阶-上下文管理与with语句
开发语言·数据结构·数据库·人工智能·pytorch·redis·python
柠檬味的Cat6 小时前
GEO优化系统哪个渠道商好
大数据·人工智能·python