When using the colormap set_over
and set_under
methods to select the color of out-of-range values that will appear in the extensions of the colorbar, only one color can be selected. I am looking for a work-around to be able to display a gradient of color in the colorbar extensions. For exemple, the last color of the colorbar I created is light pink and the extension is uniformly red. What I want instead is an extension that starts with the same light pink and that gradually becomes red.
Here's the code I used:
import matplotlib as mpl
from matplotlib.backends.backend_agg import FigureCanvasAgg
from matplotlib.colors import LinearSegmentedColormap
from matplotlib.figure import Figure
# data
bounds = [0, 15, 25, 40]
style_color = [[247, 247, 247],
[5, 113, 176],
[146, 197, 222],
[244, 165, 130],
[202, 0, 32]]
# transform color rgb value to 0-1 range
color_arr = []
for color in style_color:
rgb = [float(value)/255 for value in color]
color_arr.append(rgb)
# normalize bound values
norm = mpl.colors.Normalize(vmin=min(bounds), vmax=max(bounds))
normed_vals = norm(bounds)
# create a colormap
cmap = LinearSegmentedColormap.from_list(
'my_palette',
list(zip(normed_vals, color_arr[:-1])),
N=256
)
cmap.set_over([color for color in color_arr[-1]])
cmap.set_under([color for color in color_arr[0]])
# create a figure
fig = Figure(figsize=(2, 5))
canvas = FigureCanvasAgg(fig)
ax = fig.add_subplot(121)
# create the colorbar
cb = mpl.colorbar.ColorbarBase(ax,
cmap=cmap,
norm=norm,
extend='max',
ticks=bounds)
fig.savefig('colorbar_extensions')
Resulting colorbar:
I think the cmap.set_over
and cmap.set_under
methods are meant to highlight strict cutoffs, i.e. "highlight every value that is too high in one specific color, e.g. red".
If I understood you correctly, you want your colorbar to have a gradient towards values above a specific threshold, so simply add the threshold value to your boundaries:
# data
bounds = [0, 15, 25, 40, 45] # <- "45" is new here
style_color = [[247, 247, 247],
[5, 113, 176],
[146, 197, 222],
[244, 165, 130],
[202, 0, 32],
[255, 0, 0]] # <- the mapped color for the boundary "45" is [r,g,b] red.
Now you need to remove the call to cmap.set_over([color for color in color_arr[-1]])
and hide the respective tick from the colorbar by restricting it with ticks=bounds[:-1]
.
yields:
Note: you might want to choose this "value is above threshold" point to be closer to 40 (e.g. 41) so that the colorbar does not look so "stretched out" at the top, which will however compress the gradient so much that it nearly looks like your original plot again. In this case, you'll need to specify a different red hue as the threshold color.