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

标签 python 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)
我可以使用 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

关于python - 在 jupyter 中禁止显示 matplotlib 动画中的最后一帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63364305/

相关文章:

python - statsmodels.tsa.arima_model : TypeError: 'Series' object is not callable

python - 组内的 Pandas 排序导致重复索引

python - Jupyter Notebook 内核一直很忙

python - print() 中的结束 ='...' 键不是线程安全的?

python - 为什么 matplotlib.animation.FuncAnimation 在 Jupyter 笔记本中产生空白输出?

python - Pandas 与 MultiIndex 合并用于重复列

python - xml.etree.ElementTree.ParseError : not well-formed (invalid token) due to "<" symbol in script

python - Jupyter Notebook 中的 Selenium ,不同细胞的不同结果

python - Matplotlib 动画