在Python中嵌入Matplotlib动画(google colab笔记本)

在Python中嵌入Matplotlib动画(google colab笔记本),matplotlib,animation,gif,google-colaboratory,animated-gif,Matplotlib,Animation,Gif,Google Colaboratory,Animated Gif,我试图在谷歌的colab.research中显示一个gif文件。我能够使用以下路径名将文件保存在目录中/content/brownamotion.gif,但我不知道如何在笔记本中显示此gif 到目前为止,生成GIF的代码,以防有人操纵它不保存GIF,而是直接将其动画化到google colab文件中 # Other Brownian Motion from math import * import numpy as np import matplotlib.pyplot as plt from

我试图在谷歌的colab.research中显示一个gif文件。我能够使用以下路径名将文件保存在目录中
/content/brownamotion.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 research还不熟悉。

请查看此链接,了解如何使用HTML使其正常工作

我没有嵌入链接,而是嵌入了一个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())
基本上我们听到的只是加上


从IPython.display导入HTML
到premable,然后添加行
HTML(动画到html5\u video())
。然后,该代码生成视频并保存gif

使用相同的作者git存储库似乎我们有了一个将绘图嵌入GIF()的解决方案


对于Colab,最容易使用“jshtml”来显示matplotlib动画

你需要把它设置为

从matplotlib导入rc
rc('animation',html='jshtml')
然后,只需键入动画对象。它将显示自己

anim
这是你的一段代码


它有一个滑块,您可以在任何时间点来回运行。

为什么会在动画下方显示重复的帧?
anim