我正在尝试在我的linux服务器上运行python脚本并制作并保存一些图表。我安装了ipython
和pylab
以及matplotlib
但是当我运行脚本时出现此错误:
Traceback (most recent call last):
File "/root/dining_hall_graph.py", line 14, in <module>
from pylab import *
File "/usr/lib64/python2.7/site-packages/pylab.py", line 1, in <module>
from matplotlib.pylab import *
File "/usr/lib64/python2.7/site-packages/matplotlib/pylab.py", line 265, in <module>
from matplotlib.pyplot import *
File "/usr/lib64/python2.7/site-packages/matplotlib/pyplot.py", line 97, in <module>
_backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup()
File "/usr/lib64/python2.7/site-packages/matplotlib/backends/__init__.py", line 25, in pylab_setup
globals(),locals(),[backend_name])
File "/usr/lib64/python2.7/site-packages/matplotlib/backends/backend_gtkagg.py", line 10, in <module>
from matplotlib.backends.backend_gtk import gtk, FigureManagerGTK, FigureCanvasGTK,\
File "/usr/lib64/python2.7/site-packages/matplotlib/backends/backend_gtk.py", line 13, in <module>
import gtk; gdk = gtk.gdk
File "/usr/lib64/python2.7/site-packages/gtk-2.0/gtk/__init__.py", line 64, in <module>
_init()
File "/usr/lib64/python2.7/site-packages/gtk-2.0/gtk/__init__.py", line 52, in _init
_gtk.init_check()
RuntimeError: could not open display
在这一行from pylab import *
如何在我的linux服务器上运行的python脚本中绘制和保存图形?
由于
答案 0 :(得分:17)
你几乎不应该使用from pylab import *
。
从numpy
,scipy
和matplotlib
导入您需要的内容。
在没有显示的计算机上,您需要使用agg
后端:
您可以通过指定环境变量MPLBACKEND
$ MPLBACKEND=Agg python plot.py
或者在导入matplotlib
之前导入matplotlib.pyplot
:
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.plot([1, 2, 1])
plt.savefig('test.pdf')
要将其设为默认值,您可以创建名为matplotlibrc
的文件
在当前目录或$HOME/.config/matplotlib
中包含以下内容:
backend: Agg
您可以启用X-Forwarding,因此主机上会弹出图表:
ssh -X user@server