Matplotlib似乎需要$DISPLAY环境变量,这意味着一个正在运行的X服务器
某些web托管服务不允许运行X服务器会话
有没有一种方法可以在不运行X服务器的情况下使用matplotlib生成图形?

[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的答案是一个(完全正确!)做这件事的方式,不过你也可以simply call matplotlib.use('Agg') before importing matplotlib.pyplot,然后照常继续.

例如.

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, and gdk backends都可以在没有X-server的情况下使用.但是,默认情况下只会构建Agg后端(我想是吧?),因此,其他后端很有可能无法在您的特定安装中启用.

或者,您可以在.matplotlibrc文件中设置backend参数,让matplotlib.pyplot自动使用给定的渲染器.

Python相关问答推荐

在pandas/python中计数嵌套类别

Python—转换日期:价目表到新行

mdates定位器在图表中显示不存在的时间间隔

使用SeleniumBase保存和加载Cookie时出现问题

pytest、xdist和共享生成的文件依赖项

对数据帧进行分组,并按组间等概率抽样n行

PYTHON中的selenium不会打开 chromium URL

如何在PYTHON中向单元测试S Side_Effect发送额外参数?

迭代工具组合不会输出大于3的序列

Python:使用asyncio.StreamReader.readline()读取长行

as_index=False groupBy不支持count

Python-迭代PANAS中的数据框并替换列表中不包含字符串的值

为什么Python多处理.Process()传递队列参数并且读取比函数传递队列参数和读取更快?

如何在Polars DataFrame中使用`isin‘?

用tab键改变焦点的Qt事件

LookupError:使用Django-Configurations时未安装标签为admin&39;的应用程序

用于判断x=()的&Quot;isInstance()和Not&Quot;vs&Quot;==&Quot;

如何在Python中删除对象

如何从polars中的列表中 Select 所有列

有没有办法一次删除字典里的几个条目?