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
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:
Using
display
in a loop UseIPython.display.display(fig)
to display a figure in the output. Using a loop you would want to clear the output before a new figure is shown. Note that this technique gives in general not so smooth resluts. I would hence advice to use any of the below.import matplotlib.pyplot as pltimport matplotlib.animationimport numpy as npfrom IPython.display import display, clear_output
t = np.linspace(0,2*np.pi)x = np.sin(t)
fig, ax = plt.subplots()l, = ax.plot([0,2*np.pi],[-1,1])
animate = lambda i: l.set_data(t[:i], x[:i])
for i in range(len(x)): animate(i) clear_output(wait=True) display(fig) plt.show()Plotting animations to Jupyter Notebook: why does HTML(animator.to_html()) not work when called in an inner scope (i.e in a function)?
HTML(..)
creates a html string from an object. If this is not the last line of the cell it will not be shown. To be on the safe side, you may useIPython.display.display
display(HTML(anim.to_jshtml()))
Complete working code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation, rc
from IPython.display import HTML, display
def plot_anim_funct():
fig, ax = plt.subplots()
ax.set_xlim((0, 2))
ax.set_ylim((-2, 2))
line, = ax.plot([], [], lw=2)
def init():
line.set_data([], [])
return (line,)
def animate(i):
x = np.linspace(0, 2, 1000)
y = np.sin(2 * np.pi * (x - 0.01 * i))
line.set_data(x, y)
return (line,)
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=100, interval=20,
blit=True)
display(HTML(anim.to_jshtml()))
plot_anim_funct()Animation shows only a static picture - jupyter notebook
When I run the code you showed,
collision.mp4
will be saved locally and I can play it as an animation.
If you want to run the animation in jupyter environment, you need to install the following code.# Jupyter lab
from IPython.display import HTML
%matplotlib inline
(Omission)
# plt.show()
# jupyter lab
plt.close()
HTML(anim.to_html5_video())This is just one example of what I do. Please try this SO answer as it is very helpful.
Related Topics
Ipython Notebook Clear Cell Output in Code
Interact with Other Programs Using Python
How to Use a String as a Keyword Argument
Python: How to Remove Empty Lists from a List
Finding a Substring Within a List in Python
Any Gotchas Using Unicode_Literals in Python 2.6
How to Copy Inmemoryuploadedfile Object to Disk
Pycharm Import External Library
How to Split/Partition a Dataset into Training and Test Datasets For, E.G., Cross Validation
How to Cycle Through Line Styles in Matplotlib
How to Enable Pan and Zoom in a Qgraphicsview
Pivot String Column on Pyspark Dataframe
Can You List the Keyword Arguments a Function Receives
Initialize List to a Variable in a Dictionary Inside a Loop