【问题标题】:Embedding Matplotlib Animations in Python (google colab notebook)在 Python 中嵌入 Matplotlib 动画(google colab notebook)
【发布时间】:2020-07-21 01:26:17
【问题描述】:

我正在尝试在 google 的 colab.research 中显示一个 gif 文件。我能够将文件保存在具有以下路径名称 /content/BrowniamMotion.gif 的目录中,但我不知道如何在我的笔记本中显示此 GIF。

到目前为止生成 GIF 的代码,以防有人可以操纵它而不是保存 GIF,而是直接将其动画到 google colab 文件中,

# Other Brownian Motion
from math import *
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
import matplotlib.animation as animation

fig = plt.figure(figsize=(8,6))
ax = plt.axes(projection='3d')

N=10
#val1 = 500

x=500*np.random.random(N)
y=500*np.random.random(N)

z=500*np.random.random(N)

def frame(w):
    ax.clear()

    global x,y,z
    x=x+np.random.normal(loc=0.0,scale=50.0,size=10)
    y=y+np.random.normal(loc=0.0,scale=50.0,size=10)
    z=z+np.random.normal(loc=0.0,scale=50.0,size=10)


    plt.title("Brownian Motion")
    ax.set_xlabel('X(t)')
    ax.set_xlim3d(-500.0,500.0)
    ax.set_ylabel('Y(t)')
    ax.set_ylim3d(-500.0,500.0)
    ax.set_zlabel('Z(t)')


     ax.set_zlim3d(-500.0,500.0) 

        plot=ax.scatter

3D(x, y, z, c='r')


    return plot


anim = animation.FuncAnimation(fig, frame, frames=100, blit=False, repeat=True)

anim.save('BrowniamMotion.gif', writer = "pillow", fps=10 )  

抱歉,如果这个问题很糟糕,请说明。我是 Python 新手,正在使用 colab 研究。

【问题讨论】:

    标签: matplotlib animation gif google-colaboratory animated-gif


    【解决方案1】:

    对于 Colab,最简单的方法是使用 'jshtml' 来显示 matplotlib 动画。

    你需要设置它

    from matplotlib import rc
    rc('animation', html='jshtml')
    

    然后,只需键入您的动画对象。它会显示自己

    anim
    

    这是您的代码的workable colab

    它有一个滑块,您可以在其中随时来回运行。

    【讨论】:

    • 为什么会在动画下方显示重复的帧?
    • @JuanAlejandroGalvis 使用IPython.display.display(anim) 避免重复帧
    • 这仍然适用于 google colab 吗?我刚刚执行了它,它没有任何动画......
    【解决方案2】:

    使用相同作者的 git 存储库似乎我们有一个解决方案,可以将图嵌入为 GIF (Save Matplotlib Animations as GIFs)。

    #!apt install ffmpeg
    #!brew install imagemagick
    
    import numpy as np
    import matplotlib
    import matplotlib.pyplot as plt
    
    from matplotlib import animation, rc
    from IPython.display import HTML, Image # For GIF
    
    rc('animation', html='html5')
    np.random.seed(5)
    
    
    # Set up formatting for the movie files
    Writer = animation.writers['ffmpeg']
    writer = Writer(fps=15, metadata=dict(artist='Me'), bitrate=1800)
    
    
    def generateRandomLines(dt, N):
        dX = np.sqrt(dt) * np.random.randn(1, N)
        X = np.cumsum(dX, axis=1)
    
        dY = np.sqrt(dt) * np.random.randn(1, N)
        Y = np.cumsum(dY, axis=1)
    
        lineData = np.vstack((X, Y))
    
        return lineData
    
    
    # Returns Line2D objects
    def updateLines(num, dataLines, lines):
        for u, v in zip(lines, dataLines):
            u.set_data(v[0:2, :num])
    
        return lines
    
    N = 501 # Number of points
    T = 1.0
    dt = T/(N-1)
    
    
    fig, ax = plt.subplots()
    
    data = [generateRandomLines(dt, N)]
    
    ax = plt.axes(xlim=(-2.0, 2.0), ylim=(-2.0, 2.0))
    
    ax.set_xlabel('X(t)')
    ax.set_ylabel('Y(t)')
    ax.set_title('2D Discretized Brownian Paths')
    
    ## Create a list of line2D objects
    lines = [ax.plot(dat[0, 0:1], dat[1, 0:1])[0] for dat in data]
    
    
    ## Create the animation object
    anim = animation.FuncAnimation(fig, updateLines, N+1, fargs=(data, lines), interval=30, repeat=True, blit=False)
    
    plt.tight_layout()
    plt.show()
    
    # Save as GIF
    anim.save('animationBrownianMotion2d.gif', writer='pillow', fps=60)
    
    Image(url='animationBrownianMotion2d.gif')
    ## Uncomment to save the animation
    #anim.save('brownian2d_1path.mp4', writer=writer)
    

    【讨论】:

      【解决方案3】:

      查看此链接,了解如何使用 HTML 使其正常工作 http://louistiao.me/posts/notebooks/embedding-matplotlib-animations-in-jupyter-notebooks/

      我没有嵌入链接,而是嵌入了一个让它工作的 HTML 视频。

      # Other Brownian Motion
      from math import *
      import numpy as np
      import matplotlib.pyplot as plt
      from mpl_toolkits import mplot3d
      import matplotlib.animation as animation
      from IPython.display import HTML
      
      fig = plt.figure(figsize=(8,6))
      ax = plt.axes(projection='3d')
      
      N=10
      val1 = 600
      
      x=val1*np.random.random(N)
      y=val1*np.random.random(N)
      z=val1*np.random.random(N)
      
      def frame(w):
          ax.clear()
      
          global x,y,z
          x=x+np.random.normal(loc=0.0,scale=50.0,size=10)
          y=y+np.random.normal(loc=0.0,scale=50.0,size=10)
          z=z+np.random.normal(loc=0.0,scale=50.0,size=10)
      
      
          plt.title("Brownian Motion")
          ax.set_xlabel('X(t)')
          ax.set_xlim3d(-val1,val1)
          ax.set_ylabel('Y(t)')
          ax.set_ylim3d(-val1,val1)
          ax.set_zlabel('Z(t)')
          ax.set_zlim3d(-val1,val1) 
      
          plot=ax.scatter3D(x, y, z, c='r')
      
      
          return plot
      
      
      anim = animation.FuncAnimation(fig, frame, frames=100, blit=False, repeat=True)
      
      anim.save('BrowniamMotion.gif', writer = "pillow", fps=10 )
      HTML(anim.to_html5_video())
      

      基本上我们听到的只是添加,

      from IPython.display import HTML 到 premable,然后添加行 HTML(anim.to_html5_video())。然后,此代码会生成视频并保存 gif。

      【讨论】:

        猜你喜欢
        • 2022-01-10
        • 2018-11-04
        • 2017-05-05
        • 1970-01-01
        • 2020-11-22
        • 2020-10-10
        • 1970-01-01
        • 2020-12-30
        • 1970-01-01
        相关资源
        最近更新 更多