I want to use BoundaryNorm for mapping colors, since it maps values to integers. But I found the colormapping is not consistent given discreate image values.
I wrote test code below but found the color representation may change based on the image values.
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap, LinearSegmentedColormap
bonds = [2, 5, 9]
cmap = mpl.colors.ListedColormap(['black','blue', 'green','red'])
# cmap2.set_under('black')
# cmap2.set_over('red')
norm = mpl.colors.BoundaryNorm(bonds, cmap.N, extend='both')
fig, ax = plt.subplots(figsize=(12, 8), nrows=1, ncols=2)
I1 = np.array([[0, 1, 2, 5, 6, 25]], dtype=np.uint8)
im = ax[0].imshow(I1, cmap=cmap, norm=norm, interpolation='none')
fig.colorbar(im, ax=ax[0])
I2 = np.array([[0, 1, 2, 5, 6, 255]], dtype=np.uint8)
im2 = ax[1].imshow(I2, cmap=cmap, norm=norm, interpolation='none')
fig.colorbar(im2, ax=ax[1])
plt.show()
The figure on the left is what I am expecting for I[2]=2 to be shown as blue. However, on the right side if I simply change the last value I[5]=255, I[2]=2 now mapped to black and I[3]=5 changed from green to blue. Why the right side is not mapping according the designed colorbar?
- v<2, black
- 2<=v<5, blue
- 5<=v<9, green
- v>9, red