[英]Matplotlib animation too slow ( ~3 fps )
我需要對數據進行動畫處理,因為它們帶有2D直方圖2d(也許是后來的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嗎? 如果可以,怎么辦?
該文檔有一些不錯的示例,但對我來說,我需要了解所有功能。
感謝@Chris,我再次查看了示例,並在這里找到了這篇非常有用的文章。
正如@bmu在他使用動畫的答案中所述(請參閱文章).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
循環的每個循環迭代中for
您正在清除並繪制新圖形。 為了加快速度,您應該一次創建一個圖形,然后只需循環更新圖形的屬性和數據即可。 瀏覽一下matplotlib動畫示例,以獲取有關如何執行此操作的一些指針。 通常,它涉及到調用matplotlib.pyploy.plot
然后在循環中調用axes.set_xdata
和axes.set_ydata
。
但是,根據您的情況,請看一下matplotlib動畫示例動態圖像2 。 在此示例中,數據的生成與數據的動畫是分開的(如果您有很多數據,可能不是一個好方法)。 通過將這兩個部分拆分,您可以看到導致瓶頸的numpy.histrogram2d
或imshow
(在每個部分周圍使用time.time()
)。
ps np.random.randn
是一個偽隨機數生成器。 這些往往是簡單的線性生成器,每秒可以生成數百萬個(偽)隨機數,因此,幾乎可以肯定這不是您的瓶頸-繪制屏幕幾乎總是比任何數字運算都要慢。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.