Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python and update figure in matplotlib

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.

Thanks!

like image 750
mcfly Avatar asked Aug 01 '12 17:08

mcfly


People also ask

How do you dynamically plot in Python?

To dynamically update plot in Python matplotlib, we can call draw after we updated the plot data. to define the update_line function. In it, we call set_xdata to set the data form the x-axis. And we call set_ydata to do the same for the y-axis.


1 Answers

Try using ion from matplotlib.pyplot:

import matplotlib.pyplot as pp
pp.ion()
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):
    pp.close()

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

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

like image 80
jmetz Avatar answered Oct 03 '22 19:10

jmetz