问题描述
我正在一个项目中,该项目涉及使用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)
我可以使用capture magic
,但这会抑制一切。可以,但是我的最终目标是通过活页夹将其公开,并尽可能简化学生使用。
我在网络上看到matplotlib
动画似乎没有问题,但是这些动画使用的是情节,而不是imshow
,这可能是一个问题。
任何建议将不胜感激。 谢谢, 大卫
解决方法
这就是我从“ jupyter实验室”中寻找的相同内容得到的答案。只需添加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