dpgoldenberg
dpgoldenberg

Reputation: 63

Suppress display of final frame of animation in jupyter

I am working on a project that involves generating a matplotlib animation using pyplot.imshow for the frames. I am doing this in a jupyter notebook. I have managed to get it working, but there is one annoying bug (or feature?) left. After the animation is created, Jupyter shows the last frame of the animation in the output cell. I would like the output to include the animation, captured as html, but not this final frame. Here is a simple example:

import numpy as np
from matplotlib import animation
from IPython.display import HTML

grid = np.zeros((10,10),dtype=int)
fig1 = plt.figure(figsize=(8,8))

ax1 = fig1.add_subplot(1,1,1)
def animate(i):
    grid[i,i]=1
    ax1.imshow(grid)
    return 
ani = animation.FuncAnimation(fig1, animate,frames=10);

html = HTML(ani.to_jshtml())
display(html)

I can use the capture magic, but that suppresses everything. This would be OK, but my final goal is to make this public, via binder, and make it as simple as possible for students to use.

I have seen matplotlib animations on the web that don't seem to have this problems, but those used plot, rather than imshow, which might be an issue.

Upvotes: 6

Views: 1305

Answers (1)

r-beginners
r-beginners

Reputation: 35115

That's the answer I got from the same thing I was looking for in 'jupyter lab'. Just add plt.close().

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
from IPython.display import HTML

grid = np.zeros((10,10),dtype=int)
fig1 = plt.figure(figsize=(8,8))

ax1 = fig1.add_subplot(1,1,1)
def animate(i):
    grid[i,i]=1
    ax1.imshow(grid)
    return 
ani = animation.FuncAnimation(fig1, animate,frames=10);

html = HTML(ani.to_jshtml())
display(html)
plt.close() # update

Upvotes: 8

Related Questions