Jupyter中的内联动画

时间:2017-04-17 04:22:34

标签: python animation matplotlib jupyter-notebook ipython-notebook

我有一个python动画脚本(使用matplotlib' funcAnimation),它在Spyder中运行但在Jupyter中不运行。我尝试过以下各种建议,例如添加"%matplotlib inline"并将matplotlib后端更改为" Qt4agg",都没有成功。我也试过运行几个动画示例(来自Jupyter教程),但没有一个有效。有时我会收到错误消息,有时会出现情节,但不会生成动画。顺便说一下,我已经让pyplot.plot()使用"%matplotlib inline&#34 ;.

有没有人知道有一个使用funcAnimation的SIMPLE内联动画示例的工作Jupyter笔记本。在此先感谢您的帮助!

[注意:我在Windows 7上]

5 个答案:

答案 0 :(得分:38)

笔记本后端

'串联'表示图表显示为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以获取完整概述。

答案 1 :(得分:11)

本教程中有一个简单的示例: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

答案 2 :(得分:1)

以下是我从多个来源(包括官方示例)汇总的答案。我测试了最新版本的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')

答案 3 :(得分:1)

另一个选择:

import matplotlib.animation
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams["animation.html"] = "jshtml"
plt.rcParams['figure.dpi'] = 150  
plt.ioff()
fig, ax = plt.subplots()

x= np.linspace(0,10,100)
def animate(t):
    plt.cla()
    plt.plot(x-t,x)
    plt.xlim(0,10)

matplotlib.animation.FuncAnimation(fig, animate, frames=10)

enter image description here

答案 4 :(得分:0)

如果您有图像列表,并希望通过它们进行动画处理,则可以使用以下方式:

from keras.preprocessing.image import load_img, img_to_array
from matplotlib import animation
from IPython.display import HTML
import glob

%matplotlib inline

def plot_images(img_list):
  def init():
    img.set_data(img_list[0])
    return (img,)

  def animate(i):
    img.set_data(img_list[i])
    return (img,)

  fig = figure()
  ax = fig.gca()
  img = ax.imshow(img_list[0])
  anim = animation.FuncAnimation(fig, animate, init_func=init,
                                 frames=len(img_list), interval=20, blit=True)
  return anim

imgs = [img_to_array(load_img(i)) for i in glob.glob('*.jpg')]

HTML(plot_images(imgs).to_html5_video())