I'm generating matplotlib figures in a script which I run alternatively with or without a graphical display. I'd like the script to adjust automatically: with display, it should show the figures interactively, while without a display, it should just save them into a file.
From an answer to the question Generating matplotlib graphs without a running X server, I learnt that one can use the Agg backend for non-interactive plotting.
So I am trying with this code:
import matplotlib
try:
import matplotlib.pyplot as plt
fig = plt.figure()
havedisplay = True
except:
matplotlib.use("Agg")
import matplotlib.pyplot as plt
fig = plt.figure()
havedisplay = False
# do the plotting
if havedisplay:
plt.show()
else:
fig.savefig("myfig.png")
This works as excepted in the case with a display. However, without a display, the call to matplotlib.use
is not effective, since the display has already been chosen. It's clear that I should call matplotlib.use
before import matplotlib.pyplot
, but then I don't know how to test whether a display is available or not.
I have also tried with the experimental function matplotlib.switch_backend
instead of matplotlib.use
, but this generates a RuntimeError.
Does someone have an idea how to make the above code work as intended, or can suggest an alternative way to detect whether a display is available for matplotlib or not?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…