Skip to main content
 首页 » 编程设计

python之matplotlib 动画线图保持为空

2025年05月04日16jiqing9006

我正在尝试遵循位于 here 的基本动画教程并调整它以显示已计算的数据集,而不是每帧评估一个函数,但我被卡住了。我的数据集随着时间的推移涉及 XY 坐标,包含在列表 satxpos 和 satypos 我正在尝试创建一个动画,以便它跟踪从数据集开头开始的一条线最后,每 0.1 秒显示 1 个新点。对我出错的地方有帮助吗?

from matplotlib import pyplot as plt 
from matplotlib import animation 
import numpy as np 
 
Code here creates satxpos and satypos as lists 
 
fig = plt.figure() 
ax = plt.axes(xlim=(-1e7,1e7), ylim = (-1e7,1e7)) 
line, = ax.plot([], [], lw=2) 
 
def init(): 
    line.set_data([], []) 
    return line, 
 
def animate(i): 
    line.set_data(satxpos[i], satypos[i]) 
    return line, 
 
anim = animation.FuncAnimation(fig, animate, init_func=init, 
                               frames = len(satxpos), interval = 1, blit=True) 

编辑:代码运行没有错误,但生成一个空白绘图窗口,没有显示任何点/线,也没有任何动画。数据集生成正确,在静态图中可以正常查看。

请您参考如下方法:

为了“跟踪从数据集开始到结束的一条线”,您需要为数组编制索引,以便每个时间步长包含一个元素:

line.set_data(satxpos[:i], satypos[:i]) 

(注意 :!)

代码中的其他一切看起来都很好,因此通过上述操作您应该得到并扩展线图。然后您可能希望将 interval 设置为大于 1 的值,因为这意味着 1 毫秒的时间步长(这可能有点太快了)。我想使用 interval = 40 可能是一个好的开始。