Inline Animations in Jupyter

Matplotlib animation in Jupyter notebook creates additional empty plot

This has nothing to do with an animation.

The lines

%matplotlib inline
import matplotlib.pyplot as plt
fig, ax = plt.subplots()

will create an output with an empty figure.

You may prevent the output of a cell in jupyter notebook using %%capture.

Cell1:

%%capture
%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib.animation
plt.rcParams["animation.html"] = "jshtml"
import numpy as np

t = np.linspace(0,2*np.pi)
x = np.sin(t)

fig, ax = plt.subplots()
h = ax.axis([0,2*np.pi,-1,1])
l, = ax.plot([],[])

def animate(i):
l.set_data(t[:i], x[:i])

ani = matplotlib.animation.FuncAnimation(fig, animate, frames=len(t))

Cell2:

ani

Sample Image

How to run an animated plot inline with Jupyter Lab?

Find and click the little shield on the table frame at the bottom of the screen. Is this shield icon displaying a check mark inside the shield? Hover the mouse above the shield, does the shield then display a message:

{ Active Cell Trusted: x of y shields trusted }

It's likely there is no check mark inside the shield. The reason is the Jupyter extension is designed to be locked down.

Review the Jupyter-notebook security page: Jupyter-notebook

Overview from the security page:

  • Untrusted HTML is always sanitized
  • Untrusted JavaScript is never executed
  • Html and JavaScript in Markdown cells are never trusted
  • Outputs generated by the user are trusted
  • Any other HTML or JavaScript (in Markdown cells, output generated by owners) is never trusted

The bottom line and central question of trust is: Did the current user do this? I've found Jupyter Lab security settings make bullet-number 3 the overriding rule.

Animate / update a matplotlib plot in VS Code notebook

Looks as though vscode supports ipywidgets (https://github.com/microsoft/vscode-python/issues/3429). So you can use the ipympl backend to matplotlib.

To use it you can use the %matplotlib ipympl magic.


%matplotlib notebook does some javascript injection that is very specific to jupyter notebook, so it will not work in vscode or even jupyter lab.

Animation in iPython notebook

Some options you have for animating plots in Jupyter/IPython, using matplotlib:



Leave a reply



Submit