解决matplotlib中文乱码问题(Ubuntu16.04)

3,090 阅读2分钟

在使用Ubuntu下,训练模型处理数据过程中,路径中出现中文,在终端显示过程中,出现乱码,引发了一系列狗血的问题,在网上找了下解决方案,发现比较乱,有的也不太好用,特此整理了一下可用的一个方案,希望本文对大家有所帮助。 网上教程很多,但是折腾了好久才弄好。特此记录一下。

1.问题描述

查看matplotlib配置文件位置
>>> import matplotlib
>>> print matplotlib.matplotlib_fname()
/home/ubuntu/anaconda3/lib/python3.6/site-packages/matplotlib/mpl-data/matplotlibrc

PS:因为之前安装了两个matplotlib的库。所以这里会有问题。 
一个使用sudo apt-get install python-matplotlib安装,在root用户下。 
一个使用pip install matplotlib普通用户安装。 
后来使用 sudo apt-get remove python-matplotlib后,才能显示正常的matplotlib配置文件。

2.原因分析与解决

造成Matplotlib中文乱码是因为系统里没有SimHei字体库,需要下载SimHei字体,再配置Matplotlib。

如果我们找到系统里支持中文的字体,然后在Matplotlib里设置为默认,也就不需要再下载了。

from matplotlib.font_manager import FontManager
fm = FontManager()
mat_fonts = set(f.name for f in fm.ttflist)
print(mat_fonts)

运行以上代码,可以发现系统里有很多字体可供使用,我们找到Arial Unicode MS,设置为Matplotlib的默认字体即可。

import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = ['Arial Unicode MS']

通过以上两行代码,不用其他任何修改,即可正常显示中文。

永久解决方法

首先将windwos中fonts目录下的simhei.ttf拷贝到/home/ubuntu/anaconda3/pkgs/matplotlib-2.2.2-py36h0e671d2_1/lib/python3.6/site-packages/matplotlib/mpl-data/fonts/ttf/目录中
修改配置文件 
去除这三列之前的‘#’ 
在font.sans-serif后添加,simhei

```
#font.family         : sans-serif        
#font.sans-serif     : simhei, Bitstream Vera Sans, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif   
...
#axes.unicode_minus : False #解决负号'-'显示为方块的问题
```

删除~/.cache/matplotlib的缓冲
验证 
新建python文件,输入以下内容

# -*- coding:utf-8 -*-
from matplotlib import pyplot as plt
plt.title(u'显示中文')
plt.show()


若出现如下图的中文字符,则说明更改成功。 


最后附上simhei.ttf的链接 
simhei.ttf

参考:

blog.csdn.net/github_3393…