【5.1】matplotlib-报错--tkinter.TclError no display name

报错1:

tkinter.TclError: no display name and no $DISPLAY environment variable

官网的解释:

Many users report initial problems trying to use maptlotlib in web application servers, because by default matplotlib ships configured to work with a graphical user interface which may require an X11 connection. Since many barebones application servers do not have X11 enabled, you may get errors if you don’t configure matplotlib for use in these environments. Most importantly, you need to decide what kinds of images you want to generate (PNG, PDF, SVG) and configure the appropriate default backend. For 99% of users, this will be the Agg backend, which uses the C++ antigrain rendering engine to make nice PNGs

解决办法1:

这也是大部分人在网上诸如stackoverflow的问答平台得到的解决方案,在引入pyplot、pylab之前,要先更改matplotlib的后端模式为”Agg”。直接贴代码吧!

# do this before importing pylab or pyplot
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

解决办法2:

找到matplotlibrc文件位置

[sam@g02 /]$ python
Python 2.7.14 |Anaconda custom (64-bit)| (default, Mar 27 2018, 17:29:31)
[GCC 7.2.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> import matplotlib
>>> matplotlib.matplotlib_fname()
'/data/software/anaconda2/lib/python2.7/site-packages/matplotlib/mpl-data/matplotlibrc'

vim /data/software/anaconda2/lib/python2.7/site-packages/matplotlib/mpl-data/matplotlibrc

找到backend这里,然后将其改成Agg,如下!

# You can also deploy your own backend outside of matplotlib by
# referring to the module name (which must be in the PYTHONPATH) as
# ‘module://my_backend’.
backend : Agg

报错2

RuntimeError: Invalid DISPLAY variable

原因:

matplotlib的默认backend是TkAgg,而FltkAgg, GTK, GTKAgg, GTKCairo, TkAgg , Wx or WxAgg这几个backend都要求有GUI图形界面的,所以在ssh操作的时候会报错.

import matplotlib.pyplot as plt
Backend TkAgg is interactive backend. Turning interactive mode on.

plt.get_backend()
Out[3]: u'TkAgg'

解决方法:

指定不需要GUI的backend(Agg, Cairo, PS, PDF or SVG)

import matplotlib.pyplot as plt
plt.switch_backend('agg')

参考资料

药企,独角兽,苏州。团队长期招人,感兴趣的都可以发邮件聊聊:tiehan@sina.cn
个人公众号,比较懒,很少更新,可以在上面提问题,如果回复不及时,可发邮件给我: tiehan@sina.cn