Matplotlib动画太慢(〜3 fps) [英] Matplotlib animation too slow ( ~3 fps )
问题描述
我需要对数据进行动画处理,因为它们带有 2D histogram2d(也许是 3D 之后,但我听说 mayavi 更适合).
I need to animate data as they come with a 2D histogram2d ( maybe later 3D but as I hear mayavi is better for that ).
代码如下:
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 吗?如果可以,怎么办?
It returns 3 fps, too slow apparently. Is it the use of the numpy.random in each iteration? Should I use blit? If so how?
文档中有一些很好的例子,但对我来说,我需要了解一切都做了什么.
The docs have some nice examples but for me I need to understand what everything does.
推荐答案
Thanks to @Chris I took a look at the examples again and also found this incredibly helpful post in here.
正如@bmu 在他的回答(见帖子)中所说的那样,使用 animation.FuncAnimation 是我的方式.
As @bmu states in he's answer (see post) using animation.FuncAnimation was the way for me.
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()
这篇关于Matplotlib动画太慢(〜3 fps)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!