我在服务器中运行一个简单的python脚本:import matplotlib.pyplot as pltimport numpy as npx = np.random.randn(60)y = np.random.randn(60)plt.scatter(x, y, s=20)out_png = 'path/to/store/out_file.png'plt.savefig(out_png, dpi=150)我尝试python example.py在已安装matplotlib 1.5.1的服务器中使用该命令,但失败并显示以下错误:Traceback (most recent call last): File "example.py", line 7, in <module> plt.scatter(x, y, s=20) File "/home/USER/.virtualenvs/nnet/lib/python2.7/site-packages/matplotlib/pyplot.py", line 3241, in scatter ax = gca() File "/home/USER/.virtualenvs/nnet/lib/python2.7/site-packages/matplotlib/pyplot.py", line 928, in gca return gcf().gca(**kwargs) File "/home/USER/.virtualenvs/nnet/lib/python2.7/site-packages/matplotlib/pyplot.py", line 578, in gcf return figure() File "/home/USER/.virtualenvs/nnet/lib/python2.7/site-packages/matplotlib/pyplot.py", line 527, in figure**kwargs) File "/home/USER/.virtualenvs/nnet/lib/python2.7/site-packages/matplotlib/backends/backend_tkagg.py", line 84, in new_figure_manager return new_figure_manager_given_figure(num, figure) File "/home/USER/.virtualenvs/nnet/lib/python2.7/site-packages/matplotlib/backends/backend_tkagg.py", line 92, in new_figure_manager_given_figure window = Tk.Tk() File "/usr/local/lib/python2.7/lib-tk/Tkinter.py", line 1810, in __init__ self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)_tkinter.TclError: no display name and no $DISPLAY environment variable这是怎么回事
3 回答
一只甜甜圈
TA贡献1836条经验 获得超5个赞
您可以通过在.py脚本的非常开头添加这两行来解决此问题。
import matplotlib
matplotlib.use('Agg')
PS:如果在源代码的开头没有添加这两行,则错误仍然存在。
桃花长相依
TA贡献1860条经验 获得超8个赞
为了加总答案,我在所需脚本的开头使用了它。因此它可以在不同的环境下平稳运行。
import os
import matplotlib as mpl
if os.environ.get('DISPLAY','') == '':
print('no display found. Using non-interactive Agg backend')
mpl.use('Agg')
import matplotlib.pyplot as plt
因为我不希望它总是使用'Agg'后端,所以仅当它通过Travis CI时才使用。
添加回答
举报
0/150
提交
取消