100

This is hopefully a simple question but I can't figure it out at the moment. I want to use matplotlib to show 2 figures and then use them interactively. I create the figures with:

import matplotlib
import pylab as pl

f1 = pl.figure()
f2 = pl.figure()

and can use the MATLAB-like pyplot interface to plot and draw in both figures. With

current_figure = pl.gcf()

I can determine the currently active figure for the pyplot interface, depending on which figure I clicked in. Now I want to draw something to the first figure with the pyplot interface but the current figure can be either of them. So is there something like

pl.set_current_figure(figure)

or any workaround? (I know that I can use the object oriented interface but for interactive stuff just using commands like plot(x, y) is much nicer)

Alexander
  • 2,174
  • 3
  • 16
  • 25

2 Answers2

115

You can simply set figure f1 as the new current figure with:

pl.figure(f1.number)

Another option is to give names (or numbers) to figures, which might help make the code easier to read:

pl.figure("Share values")
# ... some plots ...
pl.figure("Profits")
# ... some plots ...

pl.figure("Share values")  # Selects the first figure again

In fact, figure "numbers" can be strings, which are arguably more explicit that simple numbers.

PS: The pyplot equivalent of pylab.figure() is matplotlib.pyplot.figure().

PPS: figure() now accepts a Figure object, so you should be able to activate figure f1 with figure(f1).

Eric O. Lebigot
  • 91,433
  • 48
  • 218
  • 260
  • 2
    Is there a good way to do this using matplotlib.figure.Figure instead of pylab?? – tylerthemiler Dec 27 '11 at 21:20
  • @tylerthemiler: Yes, but that would be `matplotlib.pyplot.figure()`. – Eric O. Lebigot Dec 27 '11 at 21:55
  • If you want to do the same thing with axes, just use `pylab.sca(my_axis)` ("set current axis"). – PiHalbe Jun 26 '13 at 13:32
  • 1
    I personally prefer using symbols and naming the symbols well (e.g., `share_values_fig` instead of `f1`), rather than passing strings. I find it's easier to detect when you have misspelled a symbol name, since Python will complain, than when you have mistyped a string, which assumes that matplotlib will complain (which it might do in this case—I don't know—but some functions would perhaps just create a new figure if it didn't recognize the string since earlier). But both options work, I guess. – HelloGoodbye Aug 08 '22 at 12:43
19

Give each figure a number:

f1 = pl.figure(1)
f2 = pl.figure(2)
# use f2
pl.figure(1) # make f1 active again
Hoa Long Tam
  • 740
  • 3
  • 6