在jupyter中禁止显示动画的最后一帧

dpg*_*erg 3 python matplotlib jupyter-notebook matplotlib-animation

我正在开发一个项目,涉及生成用于帧的matplotlib动画。pyplot.imshow我正在jupyter笔记本上做这个。我已经设法让它工作,但还剩下一个恼人的错误(或功能?)。创建动画后,Jupyter在输出单元中显示动画的最后一帧。我希望输出包含捕获为 html 的动画,但不包含最终帧。这是一个简单的例子:

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)
Run Code Online (Sandbox Code Playgroud)

我可以使用capture magic,但这会抑制一切。这没问题,但我的最终目标是通过活页夹将其公开,并使其尽可能简单地供学生使用。

我在网上看到过matplotlib动画似乎没有这个问题,但那些使用的是情节,而不是imshow,这可能是一个问题。

r-b*_*ers 6

这就是我从“jupyter lab”中寻找的相同内容中得到的答案。只需添加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
Run Code Online (Sandbox Code Playgroud)