2

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 using plt.show() or anim.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
)

enter image description here

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?

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.