Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stop / start / pause in python matplotlib animation

I'm using FuncAnimation in matplotlib's animation module for some basic animation. This function perpetually loops through the animation. Is there a way by which I can pause and restart the animation by, say, mouse clicks?

like image 488
Jaco Vermaak Avatar asked May 24 '13 10:05

Jaco Vermaak


People also ask

How do I pause Matplotlib animation?

pause() method to pause an animation. using the Animation. resume() method to resume an animation.

How do I save an animation in Python?

To save an animation, we can use Animation. save() or Animation. to_html5_video().

How does PLT pause work?

The key why plt. pause is "required" is that it starts the mock-up event-loop such that it has time to run at least once and produce the figure in completeness. After that your code can continue. While the code is running, no further events are processed.


2 Answers

Here is a FuncAnimation example which I modified to pause on mouse clicks. Since the animation is driven by a generator function, simData, when the global variable pause is True, yielding the same data makes the animation appear paused.

The value of paused is toggled by setting up an event callback:

def onClick(event):     global pause     pause ^= True fig.canvas.mpl_connect('button_press_event', onClick) 

import matplotlib.pyplot as plt import numpy as np import matplotlib.animation as animation  pause = False def simData():     t_max = 10.0     dt = 0.05     x = 0.0     t = 0.0     while t < t_max:         if not pause:             x = np.sin(np.pi*t)             t = t + dt         yield x, t  def onClick(event):     global pause     pause ^= True  def simPoints(simData):     x, t = simData[0], simData[1]     time_text.set_text(time_template%(t))     line.set_data(t, x)     return line, time_text  fig = plt.figure() ax = fig.add_subplot(111) line, = ax.plot([], [], 'bo', ms=10) ax.set_ylim(-1, 1) ax.set_xlim(0, 10)  time_template = 'Time = %.1f s' time_text = ax.text(0.05, 0.9, '', transform=ax.transAxes) fig.canvas.mpl_connect('button_press_event', onClick) ani = animation.FuncAnimation(fig, simPoints, simData, blit=False, interval=10,     repeat=True) fig.show() 
like image 120
unutbu Avatar answered Sep 20 '22 09:09

unutbu


This works...

anim = animation.FuncAnimation(fig, animfunc[,..other args])  #pause anim.event_source.stop()  #unpause anim.event_source.start() 
like image 25
fred Avatar answered Sep 17 '22 09:09

fred