我正在尝试在 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 研究。
对于 Colab,最简单的方法是使用“jshtml”来显示 matplotlib 动画。
您需要设置
from matplotlib import rc
rc('animation', html='jshtml')
然后,只需输入您的动画对象。它会自行显示
anim
这是您的代码的可行的 colab。
它有一个滑块,您可以随时来回运行。
查看此链接,了解如何使用 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
添加到序言,然后添加行 HTML(anim.to_html5_video())
。然后,此代码会生成视频并保存 gif。
使用相同作者的 git 存储库似乎我们有一个将绘图嵌入为 GIF 的解决方案(将 Matplotlib 动画另存为 GIF )。
#!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)
这是一个基于 @korakot 答案的简单解决方案,它解决了动画后有额外帧的问题:
from matplotlib import animation
from IPython.display import HTML
def frame(f):
ax.clear()
ax.plot(...your code here...)
fig = plt.figure()
ax = plt.axes()
anim = animation.FuncAnimation(fig, frame, frames=100)
plt.close()
HTML(anim.to_jshtml())
请注意,如果
HTML(...)
不在 colab 单元格的最后一行,则不会自动显示(除非您明确调用 IPython.display.display()
)。