在没有运行 X 服务器的情况下生成 matplotlib 图 [英] Generating matplotlib graphs without a running X server
问题描述
Matplotlib 似乎需要 $DISPLAY 环境变量,这意味着正在运行的 X 服务器.
某些网络托管服务不允许正在运行的 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 的答案是一种(完全有效!)方法,但您也可以 只需调用 matplotlib.use('Agg')
before导入 matplotlib.pyplot
,然后照常继续.
@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屋!