How do you get the current figure number in Python's matplotlib?

R. Wayne picture R. Wayne · Feb 19, 2017 · Viewed 13.3k times · Source

I'm playing around with an example script that shows how to switch back and forth between figures. I found the example here: http://matplotlib.org/examples/pylab_examples/multiple_figs_demo.html When I try to print out the figure number I get "Figure(640x480)" instead of the number 1 I was expecting. How do you get the number?

# Working with multiple figure windows and subplots
import matplotlib.pyplot as plt
import numpy as np

t = np.arange(0.0, 2.0, 0.01)
s1 = np.sin(2*np.pi*t)
s2 = np.sin(4*np.pi*t)

plt.figure(1)
plt.subplot(211)
plt.plot(t, s1)
plt.subplot(212)
plt.plot(t, 2*s1)

plt.figure(2)
plt.plot(t, s2)

# now switch back to figure 1 and make some changes
plt.figure(1)
plt.subplot(211)
plt.plot(t, s2, 's')
ax = plt.gca()
ax.set_xticklabels([])

# Return a list of existing figure numbers.
print "Figure numbers are = " + str(plt.get_fignums())
print "current figure = " + str(plt.gcf())
print "current axes   = " + str(plt.gca())

plt.show()

Here is the output:

Figure numbers are = [1, 2]
current figure = Figure(640x480)
current axes   = Axes(0.125,0.53;0.775x0.35)

Answer

a_guest picture a_guest · Feb 19, 2017

The Figure object has a number attribute, so you can obtain the number via

>>> plt.gcf().number