When the program starts, I want to open a window with animation, but it must be paused from the beggining.
I tried to edit the example from https://matplotlib.org/stable/gallery/animation/pause_resume.html.
from matplotlib import pyplot as plt
import matplotlib.animation as animation
import numpy as np
class PauseAnimation:
def __init__(self):
fig, ax = plt.subplots()
x = np.linspace(-0.1, 0.1, 1000)
# Start with a normal distribution
self.n0 = (1.0 / ((4 * np.pi * 2e-4 * 0.1) ** 0.5) * np.exp(-x ** 2 / (4 * 2e-4 * 0.1)))
self.p, = ax.plot(x, self.n0)
self.animation = animation.FuncAnimation(fig, self.update, frames=200, interval=50, blit=True)
self.animation.pause() # not working
self.animation.event_source.stop() # not working
self.paused = True
fig.canvas.mpl_connect('button_press_event', self.toggle_pause)
def toggle_pause(self, *args, **kwargs):
if self.paused:
self.animation.resume()
else:
self.animation.pause()
self.paused = not self.paused
def update(self, i):
self.n0 += i / 100 % 5
self.p.set_ydata(self.n0 % 20)
return self.p,
pa = PauseAnimation()
plt.show()
I added self.animation.pause()
and self.animation.event_source.stop()
, but it seems no effect, animation is still playing. How can I implement this?
To be able to pause the animation you need that the main loop is already running, that is to say, that show
has already been called.
A very simple solution is instead of pausing the animation at startup, just don't start it, for example:
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as animation
class PauseAnimation:
def __init__(self):
self.fig, ax = plt.subplots()
x = np.linspace(-0.1, 0.1, 1000)
# Start with a normal distribution
self.n0 = (1.0 / ((4 * np.pi * 2e-4 * 0.1) ** 0.5) * np.exp(-x ** 2 / (4 * 2e-4 * 0.1)))
self.p, = ax.plot(x, self.n0)
self.paused = True
self.animation = None
self.fig.canvas.mpl_connect('button_press_event', self.toggle_pause)
def toggle_pause(self, *args, **kwargs):
if self.animation is None:
self.animation = animation.FuncAnimation(
self.fig, self.update, frames=200, interval=50, blit=True)
if self.paused:
self.animation.resume()
else:
self.animation.pause()
self.paused = not self.paused
def update(self, i):
self.n0 += i / 100 % 5
self.p.set_ydata(self.n0 % 20)
return self.p,
pa = PauseAnimation()
plt.show()