【问题标题】:Animating a line plot over time in Python在 Python 中随着时间的推移动画线图
【发布时间】:2020-10-01 17:54:31
【问题描述】:

时间序列数据是随时间变化的数据。我正在尝试在 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 matplotlib.pyplot as plt。将 pyplot 导入为 py 非常令人困惑。可能在您的环境中,您需要在末尾添加 plt.show() 以便触发动画。此外,在开始时设置一些固定的 x 和 y 限制以包围整个图会很有帮助,例如ax.set_xlim(trange[0], trange[-1]); ax.set_ylim(xtraj.min()-1, xtraj.max()+1).

标签: python matplotlib animation time-series data-visualization


【解决方案1】:

检查此代码:

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

上面的代码重现了这个动画:

【讨论】:

  • 谢谢@Andrea Blengino。这很有帮助。
  • 非常感谢 :-)
  • 很高兴 Andrea,我能问一个关于在 matplotlib 中学习动画的好建议吗,除了文档之外,你会推荐你以前用过的东西吗?
  • @Konqui:即使这样也会导致我的屏幕上出现空白图。这可能是什么原因?
  • 您是否完全复制了上面的代码?如果是这样,但您仍然得到一个空的情节,请尝试针对您的问题提出一个新问题
猜你喜欢
  • 1970-01-01
  • 2014-04-15
  • 1970-01-01
  • 2021-08-10
  • 1970-01-01
相关资源
最近更新 更多