pythonmatplotlibcontourcolorbarcontourf

How to change numbers on axis of colour bar


I have produced a contour plot and have a colour bar but it's labels are such random numbers which I assume just comes from the data and I've been trying to find a way to relabel it so the numbers go from 1-12 instead and go up in integers. Is there any way I can do this? My colourbar

I tried changing the limits but it didn't change anything at all.


Solution

  • When the colour bar gradient is smooth, I've found this works well:

    enter image description here

    #Create the colour bar
    cbar = plt.colorbar() #alternatively: plt.colorbar(ticks=range(1, 13))
    
    #Adjust ticks and trim the limits
    cbar.set_ticks(range(1, 13))
    cbar.ax.set_ylim(1, 12) #optional extra, to clip the overhang
    

    If the gradient wasn't as smooth (i.e. fewer levels in the contour plot), this method wouldn't work as well.


    Reproducible example

    import matplotlib.pyplot as plt
    
    #Test data
    import numpy as np
    xx, yy = np.meshgrid(*[np.linspace(0, 1)]*2)
    z = np.cos(xx**2) * 9 + np.sin(yy**2) * 9 - 4
    
    #Plot and adjust colour bar ticks
    plt.contourf(xx, yy, z, cmap='PiYG', levels=100)
    plt.gcf().set_size_inches(8, 3)
    plt.axis('off')
    
    
    cbar = plt.colorbar(label='colour bar label')
    #alternatively: plt.colorbar(ticks=range(1, 13))
    
    #Adjust ticks and trim limits
    cbar.set_ticks(range(1, 13))
    cbar.ax.set_ylim(1, 12) #optional extra, to clip the overhang