For context: I am making lots of matplotlib plots that are controlled by ipywidgets sliders using mpl-interactions. So that all the plot updating machinery is hidden away and the easiest way to update the plot is change the value of the sliders. On occasion I succeed in making a plot that provides insight into my data - in these case I want to save an animation over all the values of the slider.
I’ve tried to accomplish this using FuncAnimation
but even with repeat=False
the animation always plays in a loop exactly once after anim.save
finishes. Is there any way to prevent this?
%matplotlib ipympl
import ipywidgets as widgets
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import animation
N = 100
slider = widgets.IntSlider(value=0, min=0, max=N)
tau = np.linspace(0.1, 2, N)
fig, ax = plt.subplots()
x = np.linspace(0, 20, 500)
lines = ax.plot(x, np.sin(tau[0] * x))
def update_lines(change):
lines[0].set_data(x, np.sin(tau[change["new"]] * x))
slider.observe(update_lines, names="value")
display(slider)
def animate(i):
update_lines({"new": i})
return []
anim = animation.FuncAnimation(fig, animate, frames=N, interval=20, repeat=False)
anim.save("anim.gif")
# neither of the below stop the extra loop :(
fig.canvas.flush_events()
anim.event_source.stop()