在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添加中文字体支持。
下载SimHei.ttf
字体。
云盘下载 (提取码:3res)
获取matplotlib
包的路径,可以在python shell
终端用如下方法获得:
>>> import matplotlib
>>> print(matplotlib.__file__)
/usr/local/lib/python3.5/dist-packages/matplotlib/__init__.py
在matplotlib
的路径下,将SimHei.ttf
复制到matplotlib/mpl-data/fonts/ttf/
目录下
cp SimHei.ttf /usr/local/lib/python3.5/dist-packages/matplotlib/mpl-data/fonts/ttf/
在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
更新配置,清除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