Python - 使用 matplotlib 为大型数据集制作动画

Python - Animating large dataset with matplotlib

对于个人项目,我正在尝试制作一个相当大的数据集(1000 行)的动画,以在 Jupyter notebook 中显示多次鸟类潜水。最后我还想添加加速度数据的子图。

我用简单的例子作为粗略的模板,比如生长线圈的例子:https://towardsdatascience.com/animations-with-matplotlib-d96375c5442c

代码本身似乎 运行 慢但很好,但是它不输出动画,只是一个静态图:

这是我当前的代码:

x = np.array(dives.index)
y = np.array(dives['depth'])
x_data, y_data = [], []

fig = plt.figure()
ax = plt.axes(xlim=(0, 1000), ylim=(min(y),max(y)))
line, = ax.plot([], [])

def init():
    line.set_data([], [])
    return line,

def animate(i):
    x_data.append(x[i])
    y_data.append(y[i])
    line.set_data(x, y)

    return line,

plt.title('Bird Dives') 

ani = animation.FuncAnimation(
    fig, animate, init_func=init, frames= 1000, interval=50, blit=True)

ani.save('./plot-test.gif')
plt.show()

为什么它只是绘制图表而不是动画图表?

是的,您的错误出在您的 animate 函数中。你有 line.set_data(x, y),它在每一帧绘制 xy 的全部内容(因此产生一个不会改变的动画图)。

您打算在 animate 函数中包含的内容是 line.set_data(x_data, y_data)

至于性能:您可以通过不创建空列表并在每次迭代时附加到它来改进它。相反,将原始数组 xy 切片更简单。请考虑以下 animate 函数:

def animate(i):
    line.set_data(x[:i], y[:i])
    return line,

话虽如此,考虑到你有一千帧,它仍然需要一些时间才能 运行。