Take the 2-minute tour ×

I've done a search on SO but haven't quite found the right "solution" to my problem. I am running a loop on some data that I wish to plot. At each step of the loop -- I plot the figure with plt.show(). However, since this is a blocking function, i am stuck until I manually close the window and then the loop continues and the next plot shows up.

What I would like to do is be able to bind a key press event to close the figure and continue the loop (rather than using the mouse to "X" out of the figure).

If this is not possible, I would like to set a timer to close the figure and continue the loop.

All my issues seem to deal with the fact that plt.show() is blocking everything else -- any way around this?

Some notes on my plots: They use the same axes, but contain a scatter plot, fill boxes, and annotations -- which are always changing.


share|improve this question

1 Answer 1

up vote 3 down vote accepted

Try using ion from matplotlib.pyplot:

import matplotlib.pyplot as pp
fig = pp.figure()

More info about ion and interactive vs non-interactive usage here

Alternatively if you want to go with the button press approach assign a callback

def moveon(event):

cid = fig.canvas.mpl_connect('key_press_event', moveon)

An event timer is more tricky because the show command is blocking, so it would probably have to involve threading.

share|improve this answer
This is a great answer. Additionally, you could put it into a GUI with something like PyQT which gives you more control and the ability to update as needed. –  TimothyAWiseman Aug 1 '12 at 17:52
This did not work for me. I used the exact same code as provided and weird things happen. What occurred was that all the figures were opened consecutively (I didn't press and buttons) and they didn't have anything in them. Also, "Not Responding" showed up and shut down my python. The pp.ion() seems to cause the issues. Help?? –  mcfly Aug 1 '12 at 19:03
@mcfly: The ion() options means execution won't pause - if you want to replace the existing plot each time, only call figure once. –  jmetz Aug 1 '12 at 19:11
@mcfly: Alternatively if you want the execution to pause, use the adding a callback approach (without ion()!) –  jmetz Aug 1 '12 at 19:12
I took out ion() and it worked well! –  mcfly Aug 2 '12 at 13:12

Your Answer


