Using matplotlib / pylab without a DISPLAY

I’ve been having issues with a web system I coded for a while now and couldn’t find a solution that worked to my satisfaction to eliminate the need of a Xvnc running to provide a virtual DISPLAY to run some commands to plot data using pylab.

Finally, today, I found the solution here and I want to share it.

import matplotlib
matplotlib.use('Agg') # Must be before importing matplotlib.pyplot or pylab!
import matplotlib.pyplot as plt

fig = plt.figure()
plt.plot(range(10))
fig.savefig('temp.png')

The solution, here, is the Agg option as the “device” to be used to plot files.

Solution in place, and I can now eliminate the requirement for Xvnc from my code and all the issues that came with it are also automatically gone.

So, here’s the code for Pylab:

import matplotlib
matplotlib.use('Agg') # Must be before importing matplotlib.pyplot or pylab!
import pylab

pylab.plot(range(10))
pylab.savefig('temp.png')

Enjoy!