Show only selected or specific matplotlib figures
It's going to be tricky to do what you want in a script; I agree with jrjc's comment - you should weed the plots you want before making them instead of trying to keep a ton of non-shown plots (they still take up memory and you have to remember to clean them up!). If you are in interactive mode, you can show individual plots using the show
method of the individual figures (e.g. fig2.show()
), as long as you've made the figures using plt.figure
, but in that case they would have been shown as they were created anyway.
Additionally, I would highly recommend against using pylab, and in particular, against using "plt" as an import alias for it. "plt" is traditionally used for pyplot, not pylab. (import matplotlib.pyplot as plt
). Pylab includes a ton of other stuff and is discouraged from use except for interactive work.
Lastly, you are overwriting "fig1" in your loop. Try saving the figures into a list instead of a single variable.
According that you have created 2 figures, but you want to show only the first one:
import random
f1, a1 = plt.subplots()
a1.plot(random.sample(range(100), 20))
f2, a2 = plt.subplots()
a2.plot(random.sample(range(100), 20))
f1.show()
will not work in a script.
As suggested in comments, you could instead close the figures you don't want to see before you call:
plt.close(f2)
plt.show()
A more generic solution that work for a large number of figures is to iterate over all figures and close them, except the one you want to show:
for fig_num in plt.get_fignums():
if figure.number != fig_num:
plt.close(figure.number)
plt.show()
Or, using generators:
[plt.close(f) for f in plt.get_fignums() if f != f1.number]
plt.show()