显示 matplotlib 动画后,如何删除 Jupyter 输出中的残差图?

How to remove a residual plot in Jupyter output after displaying a matplotlib animation?

我想使用 Matplotlib 在 Jupyter 中显示动画。这是一些基本示例:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

fig, ax = plt.subplots()
line, = ax.plot(np.random.rand(10))
ax.set_ylim(0, 1)


def update(data):
    line.set_ydata(data)
    return line,


def data_gen():
    while True:
        yield np.random.rand(10)

ani = animation.FuncAnimation(fig, update, data_gen, interval=100);

from IPython.display import HTML
HTML(ani.to_jshtml())

当我第一次 运行 代码时(或在重新启动内核之后)我得到了我想要的:

然而,当我第二次 运行 完全相同的代码时,我在左下角得到了一个剩余的代码:

我注意到当我在顶部添加 %matplotlib inline 时,即使在重新启动内核后我也得到了错误的输出。因此我的猜测是我必须在每次创建动画时将魔法命令 %matplotlib 设置为顶部的默认值,但我什至找不到 %matplotlib 是否有默认值。


我使用 Anaconda。这是我的版本: 康达版本:4.4.10 Python 版本:Python 3.6.4 :: Anaconda, Inc. IPython 版本:6.2.1 Jupyter 版本:5.4.0

我使用 plt.close() 停止了第一个(不需要的)情节,并且没有在单独的单元格中看到 运行 动画问题。我相信这个问题与评论中链接的问题类似,jupyter 会自动为前两行显示不需要的图 - fig, ax = plt.subplots() line, = ax.plot(np.random.rand(10))。我厌倦了一些建议,例如在行尾使用分号和一些不同的魔术尝试,但没有任何乐趣。毫无疑问,一个更具体的解决方案将会出现,但目前....