在不运行X服务器的情况下生成matplotlib图 [英] Generating matplotlib graphs without a running X server
问题描述
Matplotlib似乎需要$ DISPLAY环境变量,这意味着X服务器正在运行.
某些Web托管服务不允许X服务器会话在运行.
有没有一种方法可以在不运行的情况下使用matplotlib生成图形X服务器?
Matplotlib seems to require the $DISPLAY environment variable which means a running X server.
Some web hosting services do not allow a running X server session.
Is there a way to generate graphs using matplotlib without a running X server?
[username@hostname ~]$ python2.6
Python 2.6.5 (r265:79063, Nov 23 2010, 02:02:03)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import matplotlib.pyplot as plt
>>> fig = plt.figure()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/username/lib/python2.6/matplotlib-1.0.1-py2.6-linux-i686.egg/matplotlib/pyplot.py", line 270, in figure
**kwargs)
File "/home/username/lib/python2.6/matplotlib-1.0.1-py2.6-linux-i686.egg/matplotlib/backends/backend_tkagg.py", line 80, in new_figure_manager
window = Tk.Tk()
File "/usr/local/lib/python2.6/lib-tk/Tkinter.py", line 1643, in __init__
self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: no display name and no $DISPLAY environment variable
>>>
推荐答案
@Neil's answer is one (perfectly valid!) way of doing it, but you can also simply call matplotlib.use('Agg')
before importing matplotlib.pyplot
, and then continue as normal.
例如
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(range(10))
fig.savefig('temp.png')
您也不必使用Agg后端. pdf,ps,svg,agg,cairo和gdk后端都可以在没有X服务器的情况下使用.但是,默认情况下将仅构建Agg后端(我认为吗?),因此很有可能在您的特定安装中可能未启用其他后端.
You don't have to use the Agg backend, as well. The pdf, ps, svg, agg, cairo, and gdk backends can all be used without an X-server. However, only the Agg backend will be built by default (I think?), so there's a good chance that the other backends may not be enabled on your particular install.
或者,您可以仅在 .matplotlibrc
文件,以使matplotlib.pyplot
自动使用给定的渲染器.
Alternately, you can just set the backend parameter in your .matplotlibrc
file to automatically have matplotlib.pyplot
use the given renderer.
这篇关于在不运行X服务器的情况下生成matplotlib图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!