时间序列数据是随时间变化的数据。我正在尝试用 python 制作时间序列数据线图的动画。在我下面的代码中,这转化为将
xtraj
绘制为它们,并将 trange
绘制为 x。不过剧情好像不太顺利。
我在堆栈溢出上发现了类似的问题,但这里提供的解决方案似乎都不起作用。一些类似的问题是 matplotlib 动画线图保持为空、Matplotlib FuncAnimation 未对线图进行动画处理 以及参考帮助文件的教程 Animations with Matplotlib。
我首先使用第一部分创建数据并使用第二部分进行模拟。我尝试重命名将用作 y 值和 x 值的数据,以便更容易阅读。
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
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)
plt.show()
任何帮助将不胜感激。我对 Python 工作很陌生,特别是尝试制作动画图。所以如果这个问题很微不足道,我必须道歉。
总结一下我的问题:如何在 Python 中对时间序列进行动画处理,迭代时间步长(x 值)。
检查此代码:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
dt = 0.01
tfinal = 1
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, ax = plt.subplots(1, 1, figsize = (6, 6))
def animate(i):
ax.cla() # clear the previous image
ax.plot(x[:i], y[:i]) # plot the line
ax.set_xlim([x0, tfinal]) # fix the x axis
ax.set_ylim([1.1*np.min(y), 1.1*np.max(y)]) # fix the y axis
anim = animation.FuncAnimation(fig, animate, frames = len(x) + 1, interval = 1, blit = False)
plt.show()
上面的代码重现了这个动画: