14

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)
R. Wayne
  • 417
  • 1
  • 9
  • 17

1 Answers1

24

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

>>> plt.gcf().number
a_guest
  • 34,165
  • 12
  • 64
  • 118
  • 4
    Yes, that works. How did you know that? Even after knowing how to do it, I can't find any documentation on that. – R. Wayne Feb 19 '17 at 03:19
  • 1
    You can also create figures with text strings instead of numbers, for example plt.figure("first"). That might be easier to remember than numbers when you're switching between figures. Still the plt.gcf().number gives the integer "1", so it must be an automatic numbering. – R. Wayne Feb 19 '17 at 03:35
  • 2
    @R.Wayne To be honest I didn't know it before but I supposed there was such an attribute (I think the term "educated guess" applies quite well). So I checked `dir(plt.gcf())` which revealed the `number` attribute. Also `help(pyplot.figure)` provides the following information: _[...] The figure objects holds this number in a `number` attribute._ Often it is a good start to just check `dir(...)` on whatever object you want to retrieve an attribute from. `help(...)` is often useful too! – a_guest Feb 19 '17 at 16:04
  • 2
    @R.Wayne `pyplot` seems to store a number for each figure internally even if you assign it a string and whenever you don't provide a number it autoincrements it from the largest one already present. Example: `plt.figure(3); plt.gcf().number => 3`; `plt.figure(1); plt.gcf().number => 1`; `plt.figure('a'); plt.gcf().number => 4` (instead of `2` which would be still "free"). – a_guest Feb 19 '17 at 16:12