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

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