import matplotlib, os
r = os.system('python -c "import matplotlib.pyplot as plt;plt.figure()"')
if r != 0:
    matplotlib.use('Agg')
import matplotlib.pyplot as plt
fig = plt.figure()
fig.savefig('myfig.png')
Automatic detection of display availability with matplotlib