pythonmatplotlibcolorbarcolormap

How to customize the colorbar


Using this code, I don't know how to customize the colorbar. The colormaps on this webiste can't satisfy me.

shade = m.contourf(Lon,Lat,TBB,np.arange(-90, -20, 10),extend='both',cmap=plt.cm.get_cmap('jet'))       
m.colorbar(shade)

my_colorbar

I want to draw a picture like this with obvious colorbar. So, what should I do? colorbar


Solution

  • You can define your own colormap using matplotlib.colors.LinearSegmentedColormap() or matplotlib.colors.ListedColormap() and use it for your plot.

    Example:

    import numpy as np; np.random.seed(0)
    import matplotlib.pyplot as plt
    import matplotlib.colors
    
    x = np.arange(0,25)
    a = np.random.randint(0,130, size=(25,25))-115
    a = np.sort(a).reshape(25,25)
    
    colors = ["#eaa941", "#efef39", "#53a447", "#3b387f", "#48a2ba"]
    cmap= matplotlib.colors.ListedColormap(colors)
    cmap.set_under("crimson")
    cmap.set_over("w")
    norm= matplotlib.colors.Normalize(vmin=-100,vmax=-0)
    
    fig, ax = plt.subplots()
    im = ax.contourf(x,x,a, levels=[-100,-80,-60,-40,-20,0],
                     extend='both',cmap=cmap, norm=norm)
    
    fig.colorbar(im, extend="both")
    
    plt.show()
    

    enter image description here