Automatic detection of display availability with matplotlib

try this?

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')
else:
    import matplotlib.pyplot as plt
    fig = plt.figure()
    plt.show()

You can detect directly if you have a display with the OS module in python. in my case it's

>>> import os
>>> os.environ["DISPLAY"]
':0.0'

The code below works for me in Linux and Windows (where it assumes there is a display device):

import os
import matplotlib
if os.name == 'posix' and "DISPLAY" not in os.environ:
    matplotlib.use('Agg')

See https://stackoverflow.com/a/1325587/896111.

Note that the line matplotlib.use('Agg') must appear after the first import of matplotlib (otherwise you will get an error).