Ubuntu中Matplotlib绘图的中文乱码

问题引入

在Ubuntu系统中使用Matplotlib绘图,如若没有进行相关配置可能会遇到中文乱码问题。

使用以下代码作图。

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

# 这两行代码解决 plt 中文显示的问题
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

waters = ('碳酸饮料', '绿茶', '矿泉水', '果汁', '其他')
buy_number = [-6, 7, 6, 1, 2]

plt.bar(waters, buy_number)
plt.title('男性购买饮用水情况的调查结果')

plt.savefig("img.png")

在这里插入图片描述
可以看到这里的中文是乱码。

如果不加上matplotlib.use('Agg'),可能会有如下报错。

root@b3936badcf6e:~/app# python3 test_zh.py 
Traceback (most recent call last):
  File "test_zh.py", line 13, in <module>
    plt.bar(waters, buy_number)
  File "/usr/local/lib/python3.5/dist-packages/matplotlib/pyplot.py", line 2759, in bar
    ax = gca()
  File "/usr/local/lib/python3.5/dist-packages/matplotlib/pyplot.py", line 984, in gca
    return gcf().gca(**kwargs)
  File "/usr/local/lib/python3.5/dist-packages/matplotlib/pyplot.py", line 601, in gcf
    return figure()
  File "/usr/local/lib/python3.5/dist-packages/matplotlib/pyplot.py", line 548, in figure
    **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/matplotlib/backend_bases.py", line 161, in new_figure_manager
    return cls.new_figure_manager_given_figure(num, fig)
  File "/usr/local/lib/python3.5/dist-packages/matplotlib/backends/_backend_tk.py", line 1044, in new_figure_manager_given_figure
    window = Tk.Tk(className="matplotlib")
  File "/usr/lib/python3.5/tkinter/__init__.py", line 1871, in __init__
    self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: no display name and no $DISPLAY environment variable

解决方案

中文乱码的原因是系统和python缺少对中文字体的支持,我们使用以下方案位matplotlib添加中文字体支持。

1 下载字体

下载SimHei.ttf字体。
云盘下载 (提取码:3res)

2 获取库路径

获取matplotlib包的路径,可以在python shell终端用如下方法获得:

>>> import matplotlib
>>> print(matplotlib.__file__)
/usr/local/lib/python3.5/dist-packages/matplotlib/__init__.py

3 新增字体

matplotlib的路径下,将SimHei.ttf复制到matplotlib/mpl-data/fonts/ttf/目录下

cp SimHei.ttf /usr/local/lib/python3.5/dist-packages/matplotlib/mpl-data/fonts/ttf/

4 修改配置文件

matplotlib的路径下,修改matplotlib/mpl-data/matplotlibrc配置文件

# 194行,去掉注释
font.family: sans-serif
# 195行,去掉注释,增加SimHei
font.sans-serif:SimHei, DejaVu Sans, Bitstream Vera Sans, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif

5 更新配置并清除matplotlib缓存

更新配置,清除matplotlib缓存

python3 -c "from matplotlib.font_manager import _rebuild;_rebuild()"

验证效果

我们执行前文的代码,中文已经能正常显示了。
在这里插入图片描述

参考

https://blog.csdn.net/birduncle/article/details/88603677
https://blog.csdn.net/qq_38410428/article/details/82658225

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章