python - Matplotlib 动画太慢(~3 fps)

标签 python matplotlib

我需要为数据制作动画,因为它们带有 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,我再次查看了示例并找到了 this此处的帖子非常有用。

正如@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()

关于python - Matplotlib 动画太慢(~3 fps),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10956685/

相关文章:

python - 如何重新排列子图,使一个在另一个下面?

python - pygame中相机不移动

python - 将框分割成不同的图像

python - 如何合并列表? ( Pandas 数据框)

使用 Qt4 进行 Python 分散更新 - Qslider

python - 如何从 3D numpy meshgrid 中提取 2D 平面

python - 如何通过 Python 访问 Windows 屏幕键盘配件

python - 设置 Virtualenv 时出现问题

python - 我如何迭代文件列表并将它们绘制为单个图形上的子图?

python - 箱形图与箱形图有何不同?