Search code examples
pythonmatplotlibcustomizationcontourcolorbar

Customization of the colorbar in Python (truncate and add more colors)


I am a new in Python. Could you please help me to make a proper customization of the colorbar. I've already tried several variants from the web, but they don't work in proper way. I have the following graph with colorbar:

sample graph with colorbar

Here is the code:

set_cmap('rainbow')
contourf(0.5*(data1+data2))
xlabel (r'across track $\rm\,[pixels]$')
ylabel (r'along track $\rm\,[pixels]$')

cbar = plt.colorbar()
cbar.set_label('radiance', rotation=270)
title('1.6 mue (avg: 5992-6012 cm^(-1))')
# Show the major grid lines 
plt.grid(b=True, which='major', color='#666666', linestyle='-')
# Show the minor grid lines 
plt.minorticks_on()
plt.grid(b=True, which='minor', color='#666666', linestyle='-', alpha=0.4)`fig=plt.figure()

I need to truncate my colorbar to the values from 0 to 9, i.e. 0,1,2,3,4,5,6,7,8,9 and create a new color for each of the value.

P.S. Commands like cbar = plt.clim(0, 9) are not working.

Thanks in advance!


Solution

  • With levels= you can tell contourf for which values you want a new level. In this, case choosing levels=0,1,2,...,9 seems to achieve what you want.

    Note that the colors are decided in the call to contourf. The function colorbar just tries to visualize the colors that were used.

    The code below first creates some random data between 0 and 20, with an outlier valued 50. The default call to contourf is compared to one were levels is set explicitly.

    import matplotlib.pyplot as plt
    from matplotlib.patches import Ellipse
    import numpy as np
    
    N, M = 100, 300
    x = np.random.uniform(-0.1, 0.1, (N, M)).cumsum(axis=1).cumsum(axis=0)
    x -=  x.min()
    x *= 20 / x.max()
    x[-1,-1] = 50
    fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(12,4))
    cont1 = ax1.contourf(x, cmap='rainbow')
    plt.colorbar(cont1, ax=ax1)
    cont2 = ax2.contourf(x, levels=np.arange(10), cmap='rainbow')
    plt.colorbar(cont2, ax=ax2)
    plt.show()
    

    example plot