Search code examples
pythonmatplotlibcolorbar

Drawing dividers between different colors in a segmented colorbar


enter image description here

I would like to draw black horizontal dividers between the different individual colors in the segmented colorbar.

mcve

import matplotlib.pyplot as plt
from matplotlib.cm import ScalarMappable
from matplotlib.colors import BoundaryNorm

plt.plot() # dummy Axes

nmin, N = 0, 11
bounds = [nmin-0.5]+[n+0.5 for n in range(nmin, N)]
norm = BoundaryNorm(bounds, 256)
cm = plt.get_cmap('cool')

cb = plt.colorbar(ScalarMappable(norm, cm), format='%02d', ax=plt.gca())
cb.set_ticks(range(nmin, N))

plt.show()

Solution

  • Here is my method with the function axhline in a for loop, you can adjust the lines with the arguments in the doc :

    import matplotlib.pyplot as plt
    from matplotlib.cm import ScalarMappable
    from matplotlib.colors import BoundaryNorm
    
    plt.plot() # dummy Axes
    
    nmin, N = 0, 11
    bounds = [nmin-0.5]+[n+0.5 for n in range(nmin, N)]
    norm = BoundaryNorm(bounds, 256)
    cm = plt.get_cmap('cool')
    
    cb = plt.colorbar(ScalarMappable(norm, cm), format='%02d', ax=plt.gca())
    cax = cb.ax
    for bound in bounds:
        cax.axhline(bound, c='k', linewidth=0.4)
    cb.set_ticks(range(nmin, N))
    
    plt.show()
    

    Figure: enter image description here