Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 353
Shaun Avatar asked Sep 03 '26 23:09

Shaun


1 Answers

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

like image 156
James Avatar answered Sep 05 '26 15:09

James



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!