2012-06-08 120 views
2

我需要动画数据,因为它们带有2D histogram2d(也许后来3D,但我听说mayavi更好)。Matplotlib动画速度太慢(〜3 fps)

下面的代码:

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 fps的,太慢明显。是否在每次迭代中使用numpy.random?我应该使用blit吗?如果是这样如何?

该文档有一些很好的例子,但对我来说,我需要了解一切。

回答

3

感谢@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() 
1

我怀疑是在每个循环迭代中使用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是伪随机数发生器。它们往往是简单的线性发生器,每秒可以产生数百万(伪)随机数,所以这几乎肯定不是您的瓶颈 - 绘图到屏幕几乎总是比任何数字处理都慢。

+0

非常感谢@Chris我找到了适合我的解决方案。 matplotlib文档非常全面,但示例可以使用一些文档。再次,谢谢:) – storedope