I have data in a 2D matrix I want to plt.colorbar(extend = "both"), I have set my data to be maxed at 100 and mined at -100, now I want to see where my data is more than 100 (it's a saturated region) so the extent of the colorbar has to be in a different color than the colorbar is there a way to set a cmap with the tips in a different color? Like <"yellow"|"seismic"|"orange">
You can use .set_over('orange')
and .set_under('yellow')
on the colormap. If you're using a standard colormap, you should first make a copy to prevent that the original colormap gets changed. .set_extremes(over=..., under=..., bad=...)
lets you change these colors in one go. (bad
is meant for invalid values, such as np.nan
and np.inf
; bad
defaults to fully transparent).
Here is an example:
import matplotlib.pyplot as plt
import numpy as np
xmin, xmax = 0, 10
ymin, ymax = 0, 7
z = np.random.randint(-150, 150, size=(ymax, xmax))
cmap = plt.get_cmap('seismic').copy()
cmap.set_extremes(under='yellow', over='orange')
norm = plt.Normalize(-100, 100)
plt.imshow(z, cmap=cmap, norm=norm, extent=[xmin, xmax, ymin, ymax], aspect='auto')
plt.colorbar(extend='both')
plt.show()
Seaborn's heatmap takes these colors into account when choosing either white or black for annotations.
import seaborn as sns
sns.heatmap(z, annot=True, fmt='d', cmap=cmap, norm=norm, cbar_kws={'extend': 'both'})