matplotlib animation.save does not give the correct frames and iterations.
When I run the code in Jupyter with the %matplotlib notebook backend my plot runs perfectly and ends on the desired end frame (n=100). But when I playback the saved mp4, I end on n=99.
I changed the frames=130 and again notebook backend ends perfectly on n=100, implying that a.event_source.stop() was called correctly. But when I review the mp4, it ends on n=129 instead.
import matplotlib.animation as animation
import numpy as np
import matplotlib.pyplot as plt
n = 100
x = np.random.randn(n)
# create the function that will do the plotting, where curr is the current frame
def update(curr):
# check if animation is at the last frame, and if so, stop the animation a
if curr == n:
a.event_source.stop()
plt.cla()
bins = np.arange(-4, 4, 0.5)
plt.hist(x[:curr], bins=bins)
plt.axis([-4,4,0,30])
plt.gca().set_title('Sampling the Normal Distribution')
plt.gca().set_ylabel('Frequency')
plt.gca().set_xlabel('Value')
plt.annotate('n = {}'.format(curr), [3,27])
fig = plt.figure()
a = animation.FuncAnimation(fig, update, interval=10, frames=None)
a.save('norm_dist.mp4')
curr == nis not saved because you have stopped the animation. But it is still shown, because your code proceeds. You may put areturndirectly aftera.event_source.stop()to not let the function continue execution until the end.a.event_source.stop()did not change the outcome. neither did placing the stop to after the updating of the plot.returnaftera.event_source.stop()works for me - you get n=99 in the last frame on screen and in the saved file. Placing the stop to after the updating of the plot wouldn't help.