首页 文章

在jupyter笔记本之外显示动画

提问于
浏览
1

我想使用Jupyter笔记本来托管我的代码以进行演示,但我不想将动画嵌入到笔记本中 . (因为嵌入视频非常耗时 . )我想运行单元格并弹出一个屏幕,好像我在终端中运行代码一样 .

from matplotlib.animation import FuncAnimation 
from matplotlib.pyplot import plot, show, subplots, title  # annotate
from IPython.display import HTML

anim = FuncAnimation(fig, update, frames=numlin, interval=100, fargs=( 
                     d, g, lr_D, lr_G, hasFake, speed, show_sample),
                     init_func=init, blit=True, repeat=0)           
HTML(anim.to_html5_video())

Why using the notebook? 使用笔记本的主要原因是我有很多不同的实验设置 . 我想使用不同的单元格来表示不同的配置,如果人们想要查看特定配置的结果,我可以立即运行它 .

Time difference . HTML功能需要一分钟才能生成我需要的视频 . 在终端中,动画才会开始 . 我希望在 Session 期间快速原型,同时 Spectator 要求显示不同初始条件的结果 .

There is also an unexpected behavior from the notebook . 笔记本中的视频与终端中弹出的视频不同 . 笔记本中的视频在绘制时没有擦除现有的帧,使得动画看起来很乱,并且无法像对应的那样跟踪轨迹 .

Animation from the notebook's output

Animation from the terminal's output

此绘图行为是我不想使用笔记本显示动画的另一个原因 .

Will the notebook needs to show other plots. 我希望如此,但没有必要 . 如果需要,我可以打开另一个笔记本电脑 .

如果我不解释,请告诉我 .

1 回答

  • 2

    笔记本内的动画

    阅读这个问题,我想知道你是否知道 %matplotlib notebook 后端 . 虽然它会在笔记本内部显示动画,但我觉得它适合所有描述的需求 .

    %matplotlib notebook
    import matplotlib.pyplot as plt
    from matplotlib.animation import FuncAnimation 
    import numpy as np
    
    a = np.random.rand(10,4)
    fig, ax =plt.subplots()
    ax.axis([0,1,0,1])
    points1, = plt.plot([],[], ls="", marker="d", color="indigo")
    points2, = plt.plot([],[], ls="", marker="o", color="crimson")
    
    def update(i):
        points1.set_data(a[i:i+2,0],a[i:i+2,1])
        points2.set_data(a[i:i+2,2],a[i:i+2,3])
        return points1, points2
    
    anim = FuncAnimation(fig, update, frames=len(a)-1, repeat=True)
    

    请注意,使用这种动画,使用 set_data 更新数据时,无论是保存到视频还是在屏幕上显示,都显示相同的动画 . 因此,如果没有更换视频所需的时间,您可以在最初显示的方式中使用它,删除 %matplotlib notebook 并添加

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

    如果使用matplotlib 2.1,您也可以选择JavaScript动画,

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

    动画在新窗口中

    如果你想要一个窗口出现,你既不应该使用 %matplotlib inline 也不应该 %matplotlib notebook ,而是替换上面代码中的第一行

    %matplotlib tk
    

相关问题