Linux命令行使用matplotlib,报错_tkinter.TclError no display name and no $DISPLAY environment variable问题解决

此文首发于我的个人博客:zhang0peter的个人博客


问题

我在Linux命令行使用Python的matplotlib,报错

 File "/usr/lib/python3/dist-packages/matplotlib/pyplot.py", line 1466, in title
    return gca().set_title(s, *args, **kwargs)
  File "/usr/lib/python3/dist-packages/matplotlib/pyplot.py", line 950, in gca
    return gcf().gca(**kwargs)
  File "/usr/lib/python3/dist-packages/matplotlib/pyplot.py", line 586, in gcf
    return figure()
  File "/usr/lib/python3/dist-packages/matplotlib/pyplot.py", line 535, in figure
    **kwargs)
  File "/usr/lib/python3/dist-packages/matplotlib/backends/backend_tkagg.py", line 81, in new_figure_manager
    return new_figure_manager_given_figure(num, figure)
  File "/usr/lib/python3/dist-packages/matplotlib/backends/backend_tkagg.py", line 89, in new_figure_manager_given_figure
    window = Tk.Tk()
  File "/usr/lib/python3.5/tkinter/__init__.py", line 1880, in __init__
    self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: no display name and no $DISPLAY environment variable

解决

我看一了下问题,原因是命令行不能画图,而matplotlib默认选择Xwindows 作为后端,设置一下即可,注意要在导入pyplot 前就设置好
错误的设置

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

正确的设置

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