Increase contour redraw speed in matplotlib

I have a python program that displays data from a file as an outline for each line in this text file. I currently have 3 separate loops in my interface. It doesn’t matter if I read the data from a file or load it into memory before running the script, I can only get ~ 6 frames per second from contour plots.

I also tried using only one outline and the rest of the normal graphics, but the speed only increased to 7 frames per second. I don’t think it is so calculated taxed to draw a few lines. Is there any way to do this much faster? Ideally, it would be nice to get at least 30 frames per second.

The way I draw the outline is that for each line of my data, I delete the previous one:

for coll in my_contour[0].collections:
    coll.remove()

and add new

my_contour[0] = ax[0].contour(x, y, my_func, [0])

At the beginning of the code, I have plt.ion()to update the graphics when I add them.

Any help would be appreciated.

thank

+2
source share
1 answer

Here is an example of using graphics contourin animation. It uses matplotlib.animation.FuncAnimationthat makes blitting on and off easy. With blit = True, it runs at ~ 64 frames per second on my machine, without blitting ~ 55 fps. Note that you intervalmust, of course, consider fast animations; setting it to interval=10(milliseconds) will allow up to 100 frames per second, but the drawing time limits it to something slower than that.

import matplotlib.pyplot as plt
import matplotlib.animation
import numpy as np
import time

x= np.linspace(0,3*np.pi)
X,Y = np.meshgrid(x,x)
f = lambda x,y, alpha, beta :(np.sin(X+alpha)+np.sin(Y*(1+np.sin(beta)*.4)+alpha))**2
alpha=np.linspace(0, 2*np.pi, num=34)
levels= 10
cmap=plt.cm.magma


fig, ax=plt.subplots()
props = dict(boxstyle='round', facecolor='wheat')
timelabel = ax.text(0.9,0.9, "", transform=ax.transAxes, ha="right", bbox=props)
t = np.ones(10)*time.time()
p = [ax.contour(X,Y,f(X,Y,0,0), levels, cmap=cmap ) ]

def update(i):
    for tp in p[0].collections:
        tp.remove()
    p[0] = ax.contour(X,Y,f(X,Y,alpha[i],alpha[i]), levels, cmap= cmap) 
    t[1:] = t[0:-1]
    t[0] = time.time()
    timelabel.set_text("{:.3f} fps".format(-1./np.diff(t).mean()))  
    return p[0].collections+[timelabel]

ani = matplotlib.animation.FuncAnimation(fig, update, frames=len(alpha), 
                                         interval=10, blit=True, repeat=True)
plt.show()

enter image description here

, gif , .

+2

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


All Articles