【问题标题】:Python - Animating large dataset with matplotlibPython - 使用 matplotlib 为大型数据集制作动画
【发布时间】:2020-06-28 19:54:11
【问题描述】:

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

我用简单的例子作为粗略的模板,比如: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()

它只是绘制图形而不是动画图形有什么原因吗?

【问题讨论】:

    标签: python matplotlib animation jupyter-notebook visualization


    【解决方案1】:

    是的,您的错误在于您的 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,
    

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

    【讨论】:

    • 啊,我没有意识到我在函数中犯的那个错误。切片方法也确实大大加快了这个过程。非常感谢您的帮助!
    猜你喜欢
    • 2018-08-10
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 2016-11-02
    • 1970-01-01
    • 2015-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多