Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib animation too slow ( ~3 fps )

I need to animate data as they come with a 2D histogram2d ( maybe later 3D but as I hear mayavi is better for that ).

Here's the code:

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)

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.

like image 330
Kevin Avatar asked Jun 18 '26 14:06

Kevin


1 Answers

Thanks to @Chris I took a look at the examples again and also found this incredibly helpful post in here.

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()
like image 167
Kevin Avatar answered Jun 21 '26 11:06

Kevin