在Python中随时间设置线图动画

2024-09-28 17:06:29 发布

您现在位置:Python中文网/ 问答频道 /正文

时间序列数据是随时间变化的数据。我正在尝试用python制作时间序列数据的线图。在我下面的代码中,这转换为将xtraj绘制为它们,将trange绘制为x。不过,这个情节似乎不起作用

我在堆栈溢出方面发现了类似的问题,但这里提供的解决方案似乎都不起作用。一些类似的问题有matplotlib animated line plot stays emptyMatplotlib FuncAnimation not animating line plot和参考帮助文件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值)


Tags: 数据importplotmatplotlibinitnpline时间
1条回答
网友
1楼 · 发布于 2024-09-28 17:06:29

检查此代码:

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()

上面的代码将复制此动画:

enter image description here

相关问题 更多 >