Jupy中的内联动画

2024-04-25 21:37:23 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答

本教程中有一个简单的示例:http://louistiao.me/posts/notebooks/embedding-matplotlib-animations-in-jupyter-notebooks/

要总结以上教程,您基本上需要这样的东西:

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())

但是…

我很难让它起作用。本质上,问题在于上面的代码在后台使用了ffmpegx264编解码器(默认情况下),但是这些代码在我的机器上没有正确配置。解决方案是卸载它们并使用正确的配置从源代码重新生成它们。有关更多详细信息,请参见我问的问题,其中包含Andrew Heusser的有效答案:Animations in ipython (jupyter) notebook - ValueError: I/O operation on closed file

因此,首先尝试上面的to_html5_video解决方案,如果它不起作用,那么也尝试卸载/重建ffmpegx264

以下是我从多个来源(包括官方示例)得出的答案。我用Jupyter和Python的最新版本进行了测试。


    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')

笔记本电脑后端

“Inline”表示绘图显示为png图形。这些png图像无法设置动画。虽然原则上可以通过连续替换png图像来构建动画,但这可能是不希望的。

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

%matplotlib notebook

jsanimation

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

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设置为显示动画的默认值

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

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

另请参见this answer以获得完整的概述。

相关问题 更多 >