After getting a matplotlib animation to run successfully inside a Vscode Juypter notebook cell, I decided to refactor the matplotlib animation code into a function but this causes the matplotlib figure to stop showing and display a warning
UserWarning: Animation was deleted without rendering anything. This is most likely not intended. To prevent deletion, assign the Animation to a variable, e.g.
anim, that exists until you output the Animation usingplt.show()oranim.save().
Initial working code:
import matplotlib.pyplot as plt
import matplotlib.animation
import numpy as np
plt.rcParams["animation.html"] = "jshtml"
plt.rcParams["figure.dpi"] = 100
plt.ioff()
def animate(frame_num):
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x + 2*np.pi * frame_num/100)
line.set_data((x, y))
return line
fig, ax = plt.subplots()
line, = ax.plot([])
ax.set_xlim(0, 2*np.pi)
ax.set_ylim(-1.1, 1.1)
matplotlib.animation.FuncAnimation(
fig, animate, frames=10, blit=True
)
Non-working refactored code:
import matplotlib.pyplot as plt
import matplotlib.animation
import numpy as np
plt.rcParams["animation.html"] = "jshtml"
plt.rcParams["figure.dpi"] = 100
plt.ioff()
def animate(frame_num):
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x + 2*np.pi * frame_num/100)
line.set_data((x, y))
return line
def generate_animation():
fig, ax = plt.subplots()
line, = ax.plot([])
ax.set_xlim(0, 2*np.pi)
ax.set_ylim(-1.1, 1.1)
anim = matplotlib.animation.FuncAnimation(
fig, animate, frames=10, blit=True
)
plt.show()
return anim
anim = generate_animation()
Also tried adding %matplotlib notebook or %matplotlib widget to the start of the Jupyter notebook cell, but the same error occurs.
Is there a way to get the matplotlib.animation.FuncAnimation working when its running from inside a function?
