Maintaining one colorbar for maptlotlib FuncAnimation

后端 未结 3 1743
醉酒成梦
醉酒成梦 2020-12-18 10:42

I\'ve made a script which uses matplotlib\'s FuncAnimation function to animate a series of contour plots for paraboloid surface functions. I\'d lik

3条回答
  •  隐瞒了意图╮
    2020-12-18 11:15

    As usual, I got beaten to the punch by @ImportanceOfBeingErnest, but I have a slightly different approach, which I thinks works as well.

    I created a separate axe for the color bar, and I created a standalone color bar using the example from matplotlib's documentation. This requires to know the extend of the color scale before hand though.

    Then I just plot the contourf in the animation using the same colorbar and normalization.

    #Generate some lists
    def f(x,y,a):
        return a*(x**2+y**2)
    
    avals = list(np.linspace(0,1,10))
    xaxis = list(np.linspace(-2,2,9))
    yaxis = list(np.linspace(-2,2,9))
    
    xy = list(itertools.product(xaxis,yaxis))
    xy = list(map(list,xy))
    xy = np.array(xy)
    
    x = xy[:,0]
    y = xy[:,1]
    x = list(x)
    y = list(y)
    
    zlist = []
    
    for a in avals:
        z = []
        for i, xval in enumerate(x):
            z.append(f(x[i],y[i],a))
        zlist.append(z)
    
    xi = np.linspace(min(x),max(x),len(x))
    yi = np.linspace(min(y), max(y), len(y))
    
    fig,[ax,cax] = plt.subplots(1,2, gridspec_kw={"width_ratios":[10,1]})
    
    
    # Set the colormap and norm to correspond to the data for which
    # the colorbar will be used.
    cmap = mpl.cm.hsv
    norm = mpl.colors.Normalize(vmin=0, vmax=10)
    
    cb1 = mpl.colorbar.ColorbarBase(cax, cmap=cmap,
                                    norm=norm,
                                    orientation='vertical')
    
    def animate(index):
        zi = ml.griddata(x, y, zlist[index], xi, yi, interp='linear')
        ax.clear()
        contourplot = ax.contourf(xi, yi, zi, cmap=cmap, norm=norm, origin='lower')
        #cbar = plt.colorbar(contourplot)
        ax.set_title('%03d'%(index))
        return ax
    
    ani = animation.FuncAnimation(fig,animate,np.array([0,1,2,3,4,5,6,7,8,9]),interval=200,blit=False)
    

提交回复
热议问题