Jupyter 中的内联动画 [英] Inline animations in Jupyter

查看:46
本文介绍了Jupyter 中的内联动画的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 python 动画脚本(使用 matplotlib 的 funcAnimation),它在 Spyder 中运行但不在 Jupyter 中运行.我尝试遵循各种建议,例如添加%matplotlib inline"并将matplotlib后端更改为Qt4agg",但都没有成功.我还尝试运行几个示例动画(来自 Jupyter 教程),但都没有奏效.有时我会收到一条错误消息,有时会出现情节,但没有动画.顺便说一句,我已经让 pyplot.plot() 使用%matplotlib inline"工作.

I have a python animation script (using matplotlib's funcAnimation), which runs in Spyder but not in Jupyter. I have tried following various suggestions such as adding "%matplotlib inline" and changing the matplotlib backend to "Qt4agg", all without success. I have also tried running several example animations (from Jupyter tutorials), none of which have worked. Sometimes I get an error message and sometimes the plot appears, but does not animate. Incidentally, I have gotten pyplot.plot() to work using "%matplotlib inline".

有谁知道有一个使用 funcAnimation 的简单内联动画示例的工作 Jupyter 笔记本.在此先感谢您的帮助!

Does anyone know of a working Jupyter notebook with a SIMPLE inline animation example that uses funcAnimation. Thanks in advance for the help!

[注意:我使用的是 Windows 7]

[Note: I am on Windows 7]

推荐答案

notebook backend

'Inline' 表示绘图显示为 png 图形.那些 png 图像不能动画.虽然原则上可以通过连续替换 png 图像来构建动画,但这可能是不受欢迎的.

notebook backend

'Inline' means that the plots are shown as png graphics. Those png images cannot be animated. While in principle one could build an animation by successively replacing the png images, this is probably undesired.

一个解决方案是使用 notebook 后端,它与 FuncAnimation 完全兼容,因为它呈现 matplotlib 图形本身:

A solution is to use the notebook backend, which is fully compatible with FuncAnimation as it renders the matplotlib figure itself:

%matplotlib notebook

动画

从 matplotlib 2.1 开始,我们可以使用 JavaScript 创建动画.这类似于 ani.to_html5() 解决方案,不同之处在于它不需要任何视频编解码器.

jsanimation

From matplotlib 2.1 on, we can create an animation using JavaScript. This is similar to the ani.to_html5() solution, except that it does not require any video codecs.

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

一些完整的例子:

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

t = np.linspace(0,2*np.pi)
x = np.sin(t)

fig, ax = plt.subplots()
ax.axis([0,2*np.pi,-1,1])
l, = ax.plot([],[])

def animate(i):
    l.set_data(t[:i], x[:i])

ani = matplotlib.animation.FuncAnimation(fig, animate, frames=len(t))

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

或者,将 jsanimation 设为显示动画的默认值,

Alternatively, make the jsanimation the default for showing animations,

plt.rcParams["animation.html"] = "jshtml"

然后在最后简单地声明 ani 以获得动画.

Then at the end simply state ani to obtain the animation.

另请参阅此答案以获得完整概述.

Also see this answer for a complete overview.

这篇关于Jupyter 中的内联动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆