Get the list of figures in matplotlib

Solution 1:

Pyplot has get_fignums method that returns a list of figure numbers. This should do what you want:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(100)
y = -x

plt.figure()
plt.plot(x)
plt.figure()
plt.plot(y)

for i in plt.get_fignums():
    plt.figure(i)
    plt.savefig('figure%d.png' % i)

Solution 2:

The following one-liner retrieves the list of existing figures:

import matplotlib.pyplot as plt
figs = list(map(plt.figure, plt.get_fignums()))

Solution 3:

Edit: As Matti Pastell's solution shows, there is a much better way: use plt.get_fignums().


import numpy as np
import pylab
import matplotlib._pylab_helpers

x=np.random.random((10,10))
y=np.random.random((10,10))
pylab.figure()
pylab.plot(x)
pylab.figure()
pylab.plot(y)

figures=[manager.canvas.figure
         for manager in matplotlib._pylab_helpers.Gcf.get_all_fig_managers()]
print(figures)

# [<matplotlib.figure.Figure object at 0xb788ac6c>, <matplotlib.figure.Figure object at 0xa143d0c>]

for i, figure in enumerate(figures):
    figure.savefig('figure%d.png' % i)