阻止Matplotlib Jupyter笔记本显示动画图

时间:2018-07-06 15:47:54

标签: python animation matplotlib jupyter-notebook

我遇到的问题是,在jupyter笔记本中显示JavaScript动画也会显示情节:

示例代码:

fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)

def init():
    line.set_data([], [])
    return line,

def animate(i):
    x = np.linspace(0, 2, 1000)
    y = np.sin(2 * np.pi * (x - 0.01 * i))
    line.set_data(x, y)
    return line,

anim = animation.FuncAnimation(fig, animate, init_func=init,
        frames=200, interval=20, blit=True)

HTML(anim.to_jshtml())

这是输出:two images

请注意,这会产生两个图,而不仅仅是动画。

另一方面,我尝试使用以下命令运行它:

HTML(anim.to_html5_video())

但是这给了我这些错误之一:

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
~\AppData\Local\Continuum\miniconda3\lib\site-packages\matplotlib\animation.py in __getitem__(self, name)
    169         try:
--> 170             return self.avail[name]
    171         except KeyError:

KeyError: 'ffmpeg'

During handling of the above exception, another exception occurred:

RuntimeError                              Traceback (most recent call last)
<ipython-input-30-b5253c68f7fe> in <module>()
     20         frames=200, interval=20, blit=True)
     21 
---> 22 HTML(anim.to_html5_video())

~\AppData\Local\Continuum\miniconda3\lib\site-packages\matplotlib\animation.py in to_html5_video(self, embed_limit)
   1347                 # We create a writer manually so that we can get the
   1348                 # appropriate size for the tag
-> 1349                 Writer = writers[rcParams['animation.writer']]
   1350                 writer = Writer(codec='h264',
   1351                                 bitrate=rcParams['animation.bitrate'],

~\AppData\Local\Continuum\miniconda3\lib\site-packages\matplotlib\animation.py in __getitem__(self, name)
    171         except KeyError:
    172             raise RuntimeError(
--> 173                 'Requested MovieWriter ({}) not available'.format(name))
    174 
    175 

RuntimeError: Requested MovieWriter (ffmpeg) not available

和安装ffmpeg没有帮助。

2 个答案:

答案 0 :(得分:2)

我相信,因为这是因为笔记本是交互式的,所以您无需调用plt.show即可自动获得绘图。您可以调用plt.close手动将其关闭(或更改交互模式,但您可能希望将其保留用于其他用途)。

fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)
plt.close(fig)
...

我只需要确保正确安装了ffmpeg即可使HTML(anim.to_html5_video())工作。好像Python找不到它。

答案 1 :(得分:0)

那是两个不同的问题,对吗?您可以选择%%capture添加单元格的输出,然后在新的单元格中显示输出。

enter image description here

对于缺少的ffmpeg,您需要确保在系统上实际找到了ffmpeg