from matplotlib import animation
from IPython.display import HTML
# <insert animation setup code here>
anim = animation.FuncAnimation() # With arguments of course!
HTML(anim.to_html5_video())
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from IPython.display import HTML
#=========================================
# Create Fake Images using Numpy
# You don't need this in your code as you have your own imageList.
# This is used as an example.
imageList = []
x = np.linspace(0, 2 * np.pi, 120)
y = np.linspace(0, 2 * np.pi, 100).reshape(-1, 1)
for i in range(60):
x += np.pi / 15.
y += np.pi / 20.
imageList.append(np.sin(x) + np.cos(y))
#=========================================
# Animate Fake Images (in Jupyter)
def getImageFromList(x):
return imageList[x]
fig = plt.figure(figsize=(10, 10))
ims = []
for i in range(len(imageList)):
im = plt.imshow(getImageFromList(i), animated=True)
ims.append([im])
ani = animation.ArtistAnimation(fig, ims, interval=50, blit=True, repeat_delay=1000)
plt.close()
# Show the animation
HTML(ani.to_html5_video())
#=========================================
# Save animation as video (if required)
# ani.save('dynamic_images.mp4')
本教程中有一个简单的示例:http://louistiao.me/posts/notebooks/embedding-matplotlib-animations-in-jupyter-notebooks/
要总结以上教程,您基本上需要这样的东西:
但是…
我很难让它起作用。本质上,问题在于上面的代码在后台使用了
ffmpeg
和x264
编解码器(默认情况下),但是这些代码在我的机器上没有正确配置。解决方案是卸载它们并使用正确的配置从源代码重新生成它们。有关更多详细信息,请参见我问的问题,其中包含Andrew Heusser的有效答案:Animations in ipython (jupyter) notebook - ValueError: I/O operation on closed file因此,首先尝试上面的
to_html5_video
解决方案,如果它不起作用,那么也尝试卸载/重建ffmpeg
和x264
。以下是我从多个来源(包括官方示例)得出的答案。我用Jupyter和Python的最新版本进行了测试。
imageList
是唯一需要修改的东西。它是一个图像列表(您的输入)。笔记本电脑后端
“Inline”表示绘图显示为png图形。这些png图像无法设置动画。虽然原则上可以通过连续替换png图像来构建动画,但这可能是不希望的。
解决方案是使用笔记本后端,它与
FuncAnimation
完全兼容,因为它呈现matplotlib图形本身:jsanimation
从matplotlib 2.1开始,我们可以使用JavaScript创建动画。这与
ani.to_html5()
解决方案类似,只是它不需要任何视频编解码器。一些完整的例子:
或者,将jsanimation设置为显示动画的默认值
然后在最后简单地声明
ani
以获得动画。另请参见this answer以获得完整的概述。
相关问题 更多 >
编程相关推荐