Matplotlib animation too slow (~ 3 frames per second)

I need to revitalize the data as it comes with a 2D 2D histogram (maybe later 3D, but as I heard Mayavi is better for this).

Here is 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. Is numpy.random used in every iteration? Should I use blit? If so, how?

There are some nice examples in the docs, but for me I need to understand that everything does.

+2
source share
2 answers

Thanks to @Chris, I looked again at the examples and also found this incredibly useful post here.

As @bmu claims it responds (see post) via animation. FuncAnimation was a 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() 
+4
source

I suspect this is using np.histogram2d in every iteration of the loop. or that in each iteration of the for loop, you clear and draw a new drawing. To speed things up, you need to create a picture once and just update the properties and data of the figure in a loop. Check out the matplotlib animation examples for some pointers on how to do this. It usually involves calling matplotlib.pyploy.plot , then in a loop, calling axes.set_xdata and axes.set_ydata .

In your case, however, take a look at the example animation matplotlib dynamic image 2 . In this example, data generation is separate from data animation (maybe this is a great approach if you have a lot of data). Dividing the two parts upwards, you will see what causes the bottleneck, numpy.histrogram2d or imshow (use time.time() around each part).

Ps np.random.randn is a pseudo random number generator. They are usually simple linear generators that can generate many millions (psuedo-) random numbers per second, so this is almost certainly not your bottleneck. The pattern on the screen is almost always slower than any number of crunches.

+1
source

Source: https://habr.com/ru/post/1013969/


All Articles