Have you ever wanted to save a Python/Matplotlib image directly to a file instead of having it displayed in an X11 window? I needed to do this for a project where I used qsub/PBS to submit jobs to a cluster and I wanted to plot some results for each run and save them to a file. I couldn’t find a simple way to save plots to a file, and I kept getting this error in python:
no display name and no $DISPLAY environment variable
After much searching I found this solution from matplotlib’s faq page:
How To Generate Python/Matplotlib Images Without Having A Window Appear
The easiest way to do this is use a non-interactive backend such as Agg (for PNGs), PDF, SVG or PS. In your figure-generating script, just call the matplotlib.use() directive before importing pylab or pyplot:
import matplotlib.pyplot as plt
You need to make sure to call matplotlib.use() before pyplot or you will get the following error:
UserWarning: This call to matplotlib.use() has no effect because the the backend has already been chosen;
matplotlib.use() must be called *before* pylab, matplotlib.pyplot,
or matplotlib.backends is imported for the first time.
if warn: warnings.warn(_use_error_msg)
I actually had an alias set up so that I call pyplot when I open up python, so I was getting this error until I changed that. Now I don’t get the “$DISPLAY environment variable” error, because python knows to use the non-interactive backend Agg instead of trying to display to the screen.