时间序列数据是一段时间内的数据。我试图在python中对时间序列数据进行线图动画。在我下面的代码中,它被翻译成了绘制 xtraj
作为y和 trange
作为X,但该图似乎没有工作。
我在Stack overflow上找到了类似的问题,但这里提供的解决方案似乎都不奏效。一些类似的问题是 matplotlib动画线图保持为空, Matplotlib FuncAnimation不对线型图进行动画处理。 和参考帮助文件的教程 用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 = py.figure(4)
ax = py.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()
上面的代码就是这个动画的再现