我使用了这个 StackOverflow 问题中的确切代码。
当我运行这段代码时,这就是我所看到的:
我希望我能提供更多细节,但我很困惑为什么即使这个简单的例子也没有正确显示。
正如我看到你使用 Jupyter Notebook,所以你应该运行这个命令来显示matplotlib
结果:
%matplotlib inline
你也需要在那里使用HTML
from IPython.display
。然后将您的动画转换为 html 视频传递给此HTML
函数:
HTML(anim.to_html5_video())
下面有一个完整的例子。我正在使用您在问题中引用的代码并对其进行了一些更改:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
from IPython.display import HTML
dt = 0.01
tfinal = 5.0
x0 = 0
sqrtdt = np.sqrt(dt)
n = int(tfinal/dt)
xtraj = np.zeros(n+1, float)
trange = np.linspace(start=0,stop=tfinal ,num=n+1)
xtraj[0] = x0
for i in range(n):
xtraj[i+1] = xtraj[i] + np.random.normal()
x = trange
y = xtraj
# animation line plot example
fig = plt.figure(4)
ax = plt.axes(xlim=(-5, 5), ylim=(0, 5))
line, = ax.plot([], [], lw=2)
def init():
line.set_data([], [])
return line,
def animate(i):
line.set_data(x[:i], y[:i])
return line,
anim = animation.FuncAnimation(fig, animate, init_func=init, frames=len(x)+1,interval=200, blit=False)
HTML(anim.to_html5_video())