stop / start / pause in python matplotlib animation
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()
How to pause matplotlib animation for some seconds(without using any mouse clicks)?
Answer
You can do it with plt.pause()
.
I simplified a bit your code in order to use it without the unknown a
module (and its get_points()
function).
Code
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig, ax = plt.subplots(figsize=(12,8))
ax.set(xlim=(0,104), ylim=(0,68))
x_start, y_start = (50, 35)
x_end, y_end = (90, 45)
N = 20
x = np.linspace(x_start, x_end, N)
y = np.linspace(y_start, y_end, N)
sc_1 = ax.scatter([], [], color="green", zorder=4)
line, = ax.plot([], [], color="crimson", zorder=4)
sc_2 = ax.scatter([], [], color="gold", zorder=4)
def animate(i):
sc_1.set_offsets([x_start, y_start])
if i == 1:
plt.pause(2)
line.set_data(x[:i], y[:i])
if i == len(x):
plt.pause(2)
sc_2.set_offsets([x_end, y_end])
return sc_1, line, sc_2,
ani = animation.FuncAnimation(fig=fig, func=animate, interval=50, blit=True)
plt.show()
How to pause/resume matplotlib ArtistsAnimation
Although it seems that in this case a FuncAnimation
might be better suited than an ArtistAnimation
, both can be
stopped / started the same way. See this question stop / start / pause in python matplotlib animation.
The main point is that the 'private' ArtistAnimation._start()
function is not doing what you think it does. Therefore it is sensible to use the ArtistAnimation.event_source.stop()
and ArtistAnimation.event_source.start()
functions.
Below is a minimal, runnable example showing how to start/stop an ArtistAnimation
by clicking with the mouse button.
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as animation
class SomeClass():
def __init__(self):
self.pause = False
self.fig, ax = plt.subplots()
ax.set_aspect("equal")
self.movie = []
nt = 10
X,Y = np.meshgrid(np.arange(16), np.arange(16))
for t in range(nt):
data = np.sin((X+t*1)/3.)**2+ 1.5*np.cos((Y+t*1)/3.)**2
pc = ax.pcolor(data)
self.movie.append([pc])
self.ani = animation.ArtistAnimation(self.fig, self.movie, interval=100)
self.fig.canvas.mpl_connect('button_press_event', self.onClick)
plt.show()
def onClick(self, event):
if self.pause:
self.ani.event_source.stop()
else:
self.ani.event_source.start()
self.pause ^= True
a = SomeClass()
Pause matplotlib custom animation loop
You may just replace time.sleep(1)
in the else
-part with plt.pause
, just like you also did it in the if
-part.
....
plt.draw()
plt.pause(0.2)
else:
plt.pause(0.2)
The other option is of course to use a matplotlib animation, like FuncAnimation
, which has the methods .event_source.stop()
and .event_source.start()
. (As shown in two of the answers to this question: stop / start / pause in python matplotlib animation)
Related Topics
Speed of Calculating Powers (In Python)
How to Include Related Model Fields Using Django Rest Framework
How to Use Brew Installed Python as the Default Python
Python: Load Variables in a Dict into Namespace
Correct Way to Implement a Custom Popup Tkinter Dialog Box
Plotting a Fast Fourier Transform in Python
Python Dictionary Keys. "In" Complexity
Concatenate Two Numpy Arrays Vertically
Remove Namespace and Prefix from Xml in Python Using Lxml
Importing Pyspark in Python Shell
How Can This Function Be Rewritten to Implement Ordereddict
Gradient Descent Using Python and Numpy
How to Get Flask to Run on Port 80
Debugging (Displaying) SQL Command Sent to the Db by SQLalchemy
Checking If All Elements in a List Are Unique