Increase the speed of redrawing contour plot in matplotlib

前端 未结 1 1365
长发绾君心
长发绾君心 2020-12-06 03:24

I have a python program that plots the data from a file as a contour plot for each line in that text file. Currently, I have 3 separate contour plots in my interface. It doe

相关标签:
1条回答
  • 2020-12-06 04:03

    Here is an example on how to use a contour plot in an animation. It uses matplotlib.animation.FuncAnimation which makes it easy to turn blitting on and off. With blit=True it runs at ~64 fps on my machine, without blitting ~55 fps. Note that the interval must of course allow for the fast animation; setting it to interval=10 (milliseconds) would allow for up to 100 fps, 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()
    

    Note that in the animated gif above a slower frame rate is shown, since the process of saving the images takes a little longer.

    0 讨论(0)
提交回复
热议问题