Search code examples
pythonmatplotlibcolorbar

Python/Matplotlib - Colorbar indicating a mean value


Is it possible to indicate a mean value on the colorbar?

I have the following plots, showing the surface "temperature" (Radiance) of a sahara section, and now it would be nice to see the mean value on the colorbar indicated by an arrow or something.

The difference between the plots is the band/channel/wavelength the measurement was taken in and there is a slight difference. Especially, when I'm going to compare the data from season to season.

Plot showing radiance distribution of a Sahara section


Solution

  • When you add a colorbar to the plot using plt.colorbar(), matplotlib creates a new axis for the colorbar returns the colorbar object. The axis the colorbar is plotted on is scaled from 0 to 1 in both x and y and is referenced as the .ax property of the colorbar object. We can use value min and max from the colorbar to map where on the axis the mean should be drawn.

    import numpy as np
    from matplotlib import pyplot as plt
    
    data = np.random.normal(1, 4, 450).reshape(-1, 15)
    plt.imshow(data)
    # capture the colorbar object, rescale mean to the axis
    cb = plt.colorbar()
    mean_loc = (data.mean() - cb.vmin) / (cb.vmax - cb.vmin)
    
    # add a horizontal line to the colorbar axis
    cb.ax.hlines(mean_loc, 0, 1)
    
    plt.show()
    

    enter image description here