Generating a PNG with matplotlib when DISPLAY is undefined
Solution 1:
The main problem is that (on your system) matplotlib chooses an x-using backend by default. I just had the same problem on one of my servers. The solution for me was to add the following code in a place that gets read before any other pylab/matplotlib/pyplot import:
import matplotlib
# Force matplotlib to not use any Xwindows backend.
matplotlib.use('Agg')
The alternative is to set it in your .matplotlibrc
Solution 2:
Just as a complement of Reinout's answer.
The permanent way to solve this kind of problem is to edit .matplotlibrc file. Find it via
>>> import matplotlib
>>> matplotlib.matplotlib_fname()
# This is the file location in Ubuntu
'/etc/matplotlibrc'
Then modify the backend in that file to backend : Agg
. That is it.
Solution 3:
The clean answer is to take a little bit of time correctly prepare your execution environment.
The first technique you have to prepare your execution environment is to use a matplotlibrc
file, as wisely recommended by Chris Q., setting
backend : Agg
in that file. You can even control — with no code changes — how and where matplotlib looks for and finds the matplotlibrc
file.
The second technique you have to prepare your execution environment is to use the MPLBACKEND
environment variable (and inform your users to make use of it):
export MPLBACKEND="agg"
python <program_using_matplotlib.py>
This is handy because you don't even have to provide another file on disk to make this work. I have employed this approach with, for example, testing in continuous integration, and running on remote machines that do not have displays.
Hard-coding your matplotlib backend to "Agg" in your Python code is like bashing a square peg into a round hole with a big hammer, when, instead, you could have just told matplotlib it needs to be a square hole.
Solution 4:
I got the error while using matplotlib through Spark. matplotlib.use('Agg')
doesn't work for me. In the end, the following code works for me. More here
import matplotlib.pyplot as plt.
plt.switch_backend('agg')