python - 在 Python 中随时间动画线图

标签 python matplotlib animation time-series data-visualization

时间序列数据是随时间变化的数据。我正在尝试在 python 中为时间序列数据的线图设置动画。在我下面的代码中,这转化为绘图 xtraj因为他们和 trange作为 x。情节似乎并没有奏效。
我在 Stack Overflow 上发现了类似的问题,但这里提供的解决方案似乎都不起作用。一些类似的问题是matplotlib animated line plot stays empty , Matplotlib 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 值)。

最佳答案

检查此代码:

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

关于python - 在 Python 中随时间动画线图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62335385/

相关文章:

python - 单独文件中的功能较慢

python - 如何使用 matplotlib/Mayavi 创建由 2 个空间坐标定义的表面的 3D 动画?

html - 使用 CSS 悬停时如何提高旋转动画的速度?

python - 动画网络图以显示算法的进度

python - Matplotlib 多个子图图形间距按要求

python - 使用 QPropertyAnimation 进行线条动画

Python Virtualbox API

python - cython;pyside2;递归错误: maximum recursion depth exceeded while calling a Python object

python - PyMongo 返回 float 而不是整数

Python matplotlib/pylab - 3D 地毯图