Generating matplotlib graphs without a running X server


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/", line 270, in figure
  File "/home/username/lib/python2.6/matplotlib-1.0.1-py2.6-linux-i686.egg/matplotlib/backends/", line 80, in new_figure_manager
    window = Tk.Tk()
  File "/usr/local/lib/python2.6/lib-tk/", line 1643, in __init__ = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: no display name and no $DISPLAY environment variable
9/14/2015 8:37:39 PM

Accepted Answer

@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
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)

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.

Alternately, you can just set the backend parameter in your .matplotlibrc file to automatically have matplotlib.pyplot use the given renderer.

2/14/2017 12:01:46 PM

You need to use the matplotlib API directly rather than going through the pylab interface. There's a good example here:

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow