Matplotlib 动画太慢(~3 fps)

Kev*_*vin 3 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)
Run Code Online (Sandbox Code Playgroud)

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

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

Kev*_*vin 6

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

正如@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()
Run Code Online (Sandbox Code Playgroud)