Matplotlib动画太慢(~3 fps)

2024-04-24 05:55:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要动画的数据,因为他们来了一个二维直方图二维(也许稍后的三维,但正如我听说马亚维是更好的)。

代码如下:

import numpy as np
import numpy.random
import matplotlib.pyplot as plt
import time, matplotlib


plt.ion()

# Generate some test data
x = np.random.randn(50)
y = np.random.randn(50)

heatmap, xedges, yedges = np.histogram2d(x, y, bins=5)
extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]

# start counting for FPS
tstart = time.time()

for i in range(10):

    x = np.random.randn(50)
    y = np.random.randn(50)

    heatmap, xedges, yedges = np.histogram2d(x, y, bins=5)

    plt.clf()
    plt.imshow(heatmap, extent=extent)
    plt.draw()

# calculate and print FPS
print 'FPS:' , 20/(time.time()-tstart)

它返回每秒3帧,显然太慢了。是在每次迭代中使用numpy.random吗?我应该用blit吗?如果是,怎么办?

这些文档有一些很好的例子,但对我来说,我需要理解每件事的作用。


Tags: importnumpytimematplotlibasnppltrandom
2条回答

感谢@Chris,我再次查看了这些示例,并在这里找到了this非常有用的帖子。

正如@bmu在他的回答(见帖子)中所述,使用animation.FuncAnimation是我的方法。

import numpy as np
import matplotlib.pyplot as plt 
import matplotlib.animation as animation

def generate_data():
    # do calculations and stuff here
    return # an array reshaped(cols,rows) you want the color map to be  

def update(data):
    mat.set_data(data)
    return mat 

def data_gen():
    while True:
        yield generate_data()

fig, ax = plt.subplots()
mat = ax.matshow(generate_data())
plt.colorbar(mat)
ani = animation.FuncAnimation(fig, update, data_gen, interval=500,
                              save_count=50)
plt.show()

我怀疑它是在每个循环迭代中使用np.histogram2d。或者在for循环的每个循环迭代中,清除并绘制一个新图形。为了加快速度,您应该只创建一次图,并在循环中更新图的属性和数据。查看matplotlib animation examples中的一些指针,了解如何执行此操作。通常它涉及调用matplotlib.pyploy.plot,然后在循环中调用axes.set_xdataaxes.set_ydata

但是,在您的例子中,请看matplotlib动画示例dynamic image 2。在本例中,数据的生成与数据的动画分离(如果有大量数据,则可能不是一个很好的方法)。通过将这两个部分分开,您可以看到哪个部分导致了瓶颈,numpy.histrogram2dimshow(在每个部分周围使用time.time())。

p.s.np.random.randn是一个伪随机数生成器。它们往往是简单的线性生成器,每秒可以生成数百万个(psuedo-)随机数,所以这几乎肯定不是你的瓶颈——屏幕绘制几乎总是比任何数字处理都慢。

相关问题 更多 >