首页 > 解决方案 > 如何加速 Matplotlib 动画?

问题描述

我想以动画风格绘制大约 8 个月的每小时数据。我目前能够做到这一点,但是随着数据量的增加,它变得非常慢。请注意,我什至将间隔设置为仅 1 毫秒!有没有办法确保动画不会变慢?此外,如何以这种样式同时绘制多条线?

到目前为止,这是我的代码:

x = benchmark_returns.index
y = benchmark_returns['Crypto 30'] 
#Would preferrably like to plot 
#benchmark_returns[['Crypto 30', 'NASDAQ', 'Dow Jones 30', 'S&P 500']] at the same time

fig, ax = plt.subplots()
line, = ax.plot(x, y, color='k')

def update(num, x, y, line):
    line.set_data(x[:num], y[:num])
    return line,


ani = animation.FuncAnimation(fig, update,  fargs=[x, y, line],
                              interval = 1, blit=True)
plt.show()

这是我的数据框的示例:

                     Crypto 30  Dow Jones 30  NASDAQ  S&P 500
2019-06-09 00:00:00  100.00000         100.0   100.0    100.0
2019-06-09 01:00:00   95.78653         100.0   100.0    100.0
2019-06-09 02:00:00   95.78653         100.0   100.0    100.0
2019-06-09 03:00:00   95.78653         100.0   100.0    100.0
2019-06-09 04:00:00   95.78653         100.0   100.0    100.0
2019-06-09 05:00:00   95.78653         100.0   100.0    100.0
2019-06-09 06:00:00   95.78653         100.0   100.0    100.0
2019-06-09 07:00:00   95.78653         100.0   100.0    100.0
2019-06-09 08:00:00   95.78653         100.0   100.0    100.0
2019-06-09 09:00:00   95.78653         100.0   100.0    100.0

标签: pythonpandasmatplotlibanimation

解决方案


显示动画plt.show()受到计算机重绘绘图速度的限制 - 因此间隔不一定决定动画更新的实际速率。通过保存动画

ani.save("animation.mp4")

或类似的将允许您以指定的速度查看动画。


推荐阅读