iPython笔记本中的动画 [英] Animation in iPython notebook

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

问题描述

我正在尝试将动画放入iPython笔记本中,但我找不到解决方案。我看过一篇使用交互式小部件讨论过的帖子,但是我对此有几个问题:首先,我用小部件看到的每个例子都使用滑块或其他输入,而我只想让动画在单元格时自动运行运行。其次,所有文档似乎都在Jupyter的网站上过时 - 每当我下载并运行他们的笔记本时,我都会收到关于某些模块被弃用的消息,然后在文件中的某些内容无法运行,可能是因为他们试图导入和访问不再存在的文件。



我在这个主题上看到了一些其他页面,但是他们经常需要下载二进制文件或其他模块,但我部分用它来教一些学生数学和我他们让他们下载Anaconda - 我希望不要进一步混淆这个问题,让他们下载并安装更复杂的东西,而不是花时间谈论数学。



简而言之,有没有一种方法可以在iPython笔记本中创建动画,只需要使用简单的导入命令即可开箱即用,以便与Anaconda的软件一起使用?





[进一步编辑:我想我也可以说我现在想要制作的动画,尽管如果我决定的话,我真的想要对我可以制作动画的范围非常灵活。现在我正在尝试制作一个数字时钟,显示苏美尔基地的每个数字 - 60个数字,以说明不同的计数和基本系统。所以它应该最初显示|然后经过一秒钟||等等,直到10表示为<依此类推,直到最后时钟滴答到一分钟,现在显示|:|代表一分钟,一秒。]

解决方案

使用matplotlib在Jupyter / IPython中制作动画图的一些选项: / p>


  • 在循环中使用显示 使用 IPython.display.display(图)在输出中显示一个数字。使用循环,您需要在显示新图形之前清除输出。请注意,此技术通常不会提供如此平滑的重新排列。因此我建议使用以下任何一种。

     将matplotlib.pyplot导入pltimport matplotlib.animationimport numpy as npfrom IPython。显示导入显示,clear_outputt = np.linspace(0,2 * np.pi)x = np.sin(t)fig,ax = plt.subplots()l,= ax.plot([0,2 * np.pi ],[ -  1,1])animate = lambda i:l.set_data(t [:i],x [:i])for i in range(len(x)):animate(i)clear_output(wait = True )display(fig)plt.show() 


  • %matplotlib notebook 使用IPython magic %matplotlib notebook 将后端设置为笔记本后端。这将使图形保持活着而不是显示静态png文件,因此也可以显示动画。

    完整示例:

     %matplotlib notebookimport matplotlib.pyplot as pltimport matplotlib.animationimport numpy as npt = np.linspace(0,2 * np.pi)x = np.sin(t)fig,ax = plt.subplots()l ,= ax.plot([0,2 * np.pi],[ -  1,1])animate = lambda i:l.set_data(t [:i],x [:i])ani = matplotlib.animation。 FuncAnimation(图,动画,帧= len(t))plt.show() 


  • %matplotlib tk 使用IPython magic %matplotlib tk 将后端设置为tk后端。这将在新的绘图窗口中打开图形,该窗口是交互式的,因此也可以显示动画。

    完整示例:

     %matplotlib tkimport matplotlib.pyplot as pltimport matplotlib.animationimport numpy as npt = np.linspace(0,2 * np.pi)x = np.sin(t)fig,ax = plt.subplots() l,= ax.plot([0,2 * np.pi],[ -  1,1])animate = lambda i:l.set_data(t [:i],x [:i])ani = matplotlib.animation .FuncAnimation(图,动画,帧= len(t))plt.show() 


  • 将动画转换为mp4视频(已由@Perfi提及的选项):

     来自IPython.display导入HTML 
    HTML(ani.to_html5_video())

    或者在no的开头使用 plt.rcParams [animation.html] =html5 tebook。
    这需要有ffmpeg视频编解码器才能转换为HTML5视频。然后视频以内联方式显示。因此,这与%matplotlib内联后端兼容。完整示例:

     %matplotlib inlineimport matplotlib.pyplot as pltplt.rcParams [animation.html] =html5import matplotlib.animationimport numpy as npt = np.linspace(0,2 * np.pi)x = np.sin(t)fig,ax = plt.subplots()l,= ax.plot([0,2 * np。 pi],[ -  1,1])animate = lambda i:l.set_data(t [:i],x [:i])ani = matplotlib.animation.FuncAnimation(图,动画,帧= len(t)) ani  

     %matplotlib inlineimport matplotlib.pyplot as pltimport matplotlib.animationimport numpy as npt = np.linspace(0,2 * np.pi)x = np.sin(t)fig,ax = plt.subplots()l,= ax.plot([ 0,2 * np.pi],[ -  1,1])灵魂te = lambda i:l.set_data(t [:i],x [:i])ani = matplotlib.animation.FuncAnimation(fig,animate,frames = len(t))来自IPython.display导入HTMLHTML(ani.to_html5_video) ()) 


  • 将动画转换为JavaScript

     来自IPython.display导入HTML 
    HTML(ani.to_jshtml())

    或使用 plt.rcParams [animation.html] =jshtml在笔记本的开头。
    这将使用JavaScript将动画显示为HTML。这与大多数新浏览器以及%matplotlib内联后端高度兼容。它在matplotlib 2.1或更高版本中可用。

    完整示例:

     %matplotlib inlineimport matplotlib.pyplot如pltplt.rcParams [animation.html] =jshtml导入matplotlib.animationimport numpy为npt = np.linspace(0,2 * np.pi)x = np.sin(t)fig,ax = plt.subplots ()l,= ax.plot([0,2 * np.pi],[ -  1,1])animate = lambda i:l.set_data(t [:i],x [:i])ani = matplotlib .animation.FuncAnimation(图,动画,帧= len(t))ani  

     %matplotlib inlineimport matplotlib.pyplot as pltimport matplotlib.animationimport numpy as npt = np.linspace(0,2 * np.pi)x = np.sin(t)fig , 一个x = plt.subplots()l,= ax.plot([0,2 * np.pi],[ -  1,1])animate = lambda i:l.set_data(t [:i],x [:i] ])来自IPython.display的ani = matplotlib.animation.FuncAnimation(fig,animate,frames = len(t))导入HTMLHTML(ani.to_jshtml()) 



I am trying to put animations in an iPython notebook and am not finding a solution. I saw one post that discussed using interactive widgets, but there are a couple problems that I have with this: First, every example I see with widgets uses a slider or some other input, whereas I just want the animation to run automatically when the cell is run. Second, all the documentation seems out of date on Jupyter's site--whenever I download and run their notebooks I get these messages about certain modules being deprecated and then later in the file something fails to run, presumably because they're trying to import and access files that no longer exist.

I've seen a few other pages on the topic but they often require downloading binaries or other modules, but I'm partly using this to teach some students Math and I've gotten them to download Anaconda--I was hoping to not further confuse the issue by making them also download and install more complicated things all while spending time not talking about the Math.

So in short, is there a way that I can create animations in an iPython notebook that only require the use of simple import commands that will run out-of-the-box so to speak with the software that comes from Anaconda?

[Edit: I should also note that I've used Tkinter to make animations, and I could make one in matplotlib I'm sure. So if there were a way to get the animations you produce with those to render in an iPython notebook, that would certainly be a working solution for me.]

[Further edit: I suppose I could also say what I am hoping to animate at the moment, although I really want to be pretty flexible about the range of things I could animate if I decide to. Right now I'm trying to make a digital clock that displays each digit in Sumerian base-60 numerals to illustrate a different counting and base system. So it should initially display | then after a second || and so on until ten gets represented as < and so on until eventually the clock ticks over to a minute where it now displays |:| to represent one minute, one second.]

解决方案

Some options you have for animating plots in Jupyter/IPython, using matplotlib:

  • Using display in a loop Use IPython.display.display(fig) to display a figure in the output. Using a loop you would want to clear the output before a new figure is shown. Note that this technique gives in general not so smooth resluts. I would hence advice to use any of the below.

    import matplotlib.pyplot as plt
    import matplotlib.animation
    import numpy as np
    from IPython.display import display, clear_output
    
    t = np.linspace(0,2*np.pi)
    x = np.sin(t)
    
    fig, ax = plt.subplots()
    l, = ax.plot([0,2*np.pi],[-1,1])
    
    animate = lambda i: l.set_data(t[:i], x[:i])
    
    for i in range(len(x)):
        animate(i)
        clear_output(wait=True)
        display(fig)
        
    plt.show()

  • %matplotlib notebook Use IPython magic %matplotlib notebook to set the backend to the notebook backend. This will keep the figure alive instead of displaying a static png file and can hence also show animations.
    Complete example:

    %matplotlib notebook
    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()
    l, = ax.plot([0,2*np.pi],[-1,1])
    
    animate = lambda i: l.set_data(t[:i], x[:i])
    
    ani = matplotlib.animation.FuncAnimation(fig, animate, frames=len(t))
    
    plt.show()

  • %matplotlib tk Use IPython magic %matplotlib tk to set the backend to the tk backend. This will open the figure in a new plotting window, which is interactive and can thus also show animations.
    Complete example:

    %matplotlib tk
    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()
    l, = ax.plot([0,2*np.pi],[-1,1])
    
    animate = lambda i: l.set_data(t[:i], x[:i])
    
    ani = matplotlib.animation.FuncAnimation(fig, animate, frames=len(t))
    
    plt.show()

  • Convert animation to mp4 video (option mentionned by @Perfi already):

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

    or use plt.rcParams["animation.html"] = "html5" at the beginning of the notebook. This will require to have ffmpeg video codecs available to convert to HTML5 video. The video is then shown inline. This is therefore compatible with %matplotlib inline backend. Complete example:

    %matplotlib inline
    import matplotlib.pyplot as plt
    plt.rcParams["animation.html"] = "html5"
    import matplotlib.animation
    import numpy as np
    
    t = np.linspace(0,2*np.pi)
    x = np.sin(t)
    
    fig, ax = plt.subplots()
    l, = ax.plot([0,2*np.pi],[-1,1])
    
    animate = lambda i: l.set_data(t[:i], x[:i])
    
    ani = matplotlib.animation.FuncAnimation(fig, animate, frames=len(t))
    ani

    %matplotlib inline
    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()
    l, = ax.plot([0,2*np.pi],[-1,1])
    
    animate = lambda 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_html5_video())

  • Convert animation to JavaScript:

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

    or use plt.rcParams["animation.html"] = "jshtml" at the beginning of the notebook. This will display the animation as HTML with JavaScript. This highly compatible with most new browsers and also with the %matplotlib inline backend. It is available in matplotlib 2.1 or higher.
    Complete example:

    %matplotlib inline
    import matplotlib.pyplot as plt
    plt.rcParams["animation.html"] = "jshtml"
    import matplotlib.animation
    import numpy as np
    
    t = np.linspace(0,2*np.pi)
    x = np.sin(t)
    
    fig, ax = plt.subplots()
    l, = ax.plot([0,2*np.pi],[-1,1])
    
    animate = lambda i: l.set_data(t[:i], x[:i])
    
    ani = matplotlib.animation.FuncAnimation(fig, animate, frames=len(t))
    ani

    %matplotlib inline
    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()
    l, = ax.plot([0,2*np.pi],[-1,1])
    
    animate = lambda 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())

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

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