Matplotlib动画太慢(~3 fps)

时间:2012-06-08 22:21:39

标签: python matplotlib

我需要为数据设置动画,因为它们带有2D histogram2d(可能是后来的3D,但我听说mayavi更好)。

以下是代码:

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吗?如果是这样的话?

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

2 个答案:

答案 0 :(得分:4)

感谢@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 :(得分: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是一个伪随机数生成器。这些往往是简单的线性生成器,每秒可以生成数百万(伪)随机数,所以这几乎肯定不是你的瓶颈 - 绘制到屏幕几乎总是比任何数字运算都慢。