1

I copied code from the manual:

%matplotlib notebook

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np

fig, ax = plt.subplots()
t = np.linspace(0, 3, 40)
g = -9.81
v0 = 12
z = g * t**2 / 2 + v0 * t

v02 = 5
z2 = g * t**2 / 2 + v02 * t

scat = ax.scatter(t[0], z[0], c="b", s=5, label=f'v0 = {v0} m/s')
line2 = ax.plot(t[0], z2[0], label=f'v0 = {v02} m/s')[0]
ax.set(xlim=[0, 3], ylim=[-4, 10], xlabel='Time [s]', ylabel='Z [m]')
ax.legend()


def update(frame):
    # for each frame, update the data stored on each artist.
    x = t[:frame]
    y = z[:frame]
    # update the scatter plot:
    data = np.stack([x, y]).T
    scat.set_offsets(data)
    # update the line plot:
    line2.set_xdata(t[:frame])
    line2.set_ydata(z2[:frame])
    return (scat, line2)


ani = animation.FuncAnimation(fig=fig, func=update, frames=40, interval=30)
plt.show()

into a new notebook and run it.

Alas, all I see is the figure:

enter image description here

(and the cell is marked with *).

When I restart the kernel, sometimes I get the beginning of the animation:

enter image description here

but I never get the controls present in the matplotlib manual.

Server Information:
You are using Jupyter Notebook.

The version of the notebook server is: 6.5.4-762f3618
The server is running on this version of Python:
Python 3.10.6 (main, May 29 2023, 11:10:38) [GCC 11.3.0]

Current Kernel Information:
Python 3.10.6 (main, May 29 2023, 11:10:38) [GCC 11.3.0]

I can save the animation in an mp4 file and view it, but I would much prefer the interactive facility.

What am I doing wrong?

sds
  • 58,617
  • 29
  • 161
  • 278
  • Short answer: The code provided on that page only produces an animation and does not include the play, pause, etc buttons. Those would need to be added using `matplotlib.widgets`. – jared Jul 06 '23 at 19:56

1 Answers1

1

Include the following after importing the libraries:

from matplotlib import rc
rc('animation', html='jshtml')

Then call ani here:

ani = animation.FuncAnimation(fig=fig, func=update, frames=40, interval=30)
plt.show()
ani

This would bring the interactive window.

Ro.oT
  • 623
  • 6
  • 15
  • This works, thank you! However, I still need to restart the kernel if I want to run another animation. Any comments on that? Moreover, after the animation, no output is produced by any cell anymore - until kernel restart. – sds Jul 06 '23 at 20:09
  • No worries! I actually tested the code on Google colab and it's running without any issue. I guess the kernel crashing issue is related to jupyter-notebook. This thread might be helpful to overcome your issue: https://stackoverflow.com/a/69788527/12317368. – Ro.oT Jul 06 '23 at 20:27