2012-06-08 122 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