问题描述

在 Linux 系统中,使用 matplotlib 绘制图形时,可能会遇到中文乱码的问题。即使已经设置了中文字体,但是显示的中文仍然是乱码。这是因为 matplotlib 默认使用的字体库没有包含中文字体。所以,需要对 matplotlib 进行配置,使其可以正确显示中文。

解决方案

1. 安装中文字体

为了能够正确显示中文,首先需要安装中文字体。可以通过以下命令安装中文字体:

sudo apt-get install ttf-wqy-zenhei
Plain text

安装完成后,系统将会拥有一个中文字体,可以通过指定该字体来解决 matplotlib 中文乱码问题。

2. 配置 matplotlib

对 matplotlib 进行配置,使其可以使用中文字体。首先需要找到 matplotlib 的配置文件 matplotlibrc,一般位于用户的家目录下的隐藏文件夹 .matplotlib 中。可以通过以下命令找到该文件:

find ~/.matplotlib -name matplotlibrc
Plain text

找到该文件后,使用文本编辑器打开该文件:

vi ~/.matplotlib/matplotlibrc
Plain text

在文件中,可以找到以下两行代码:

#font.sans-serif : Bitstream Vera Sans, Arial, Helvetica, sans-serif
#axes.unicode_minus : True
Plain text

将这两行代码的注释去掉,并且将 font.sans-serif 的值设置为中文字体的名称,比如 "WenQuanYi Zen Hei"。修改后的代码如下所示:

font.sans-serif : WenQuanYi Zen Hei, Bitstream Vera Sans, Arial, Helvetica, sans-serif
axes.unicode_minus : True
Plain text

保存文件后,关闭编辑器。

3. 重启 Python 环境

应用新的配置需要重启 Python 环境,这样才能使 matplotlib 使用新的字体库。关闭所有已经打开的 Python 终端窗口,然后重新启动一个新的 Python 环境。

python
Plain text

在新的 Python 终端中,导入 matplotlib,并设置中文显示:

import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['WenQuanYi Zen Hei'] 
plt.rcParams['axes.unicode_minus']=False
Python

之后,就可以正常绘制中文图形了。

总结

通过安装中文字体、配置 matplotlib,并重启 Python 环境,就可以彻底解决 Linux 中 matplotlib 中文乱码的问题了。这种方法适用于大多数 Linux 发行版,可以在终端或者 Jupyter Notebook 等环境下使用。