Question

I'm trying to create a completely custom legend (i.e. I don't want to use plt.legend or plt.colorbar. Based on a colormap, I'd like to be able to get the colors at different points in the colormap.

gradient2n = LinearSegmentedColormap.from_list('gradient2n', ["white", "red"])
breaks = [0, 0.25, 0.5, 0.75, 1.0]
# something like this
print plt.colors_at_breaks(gradient2n, breaks)
["white", "light pink", "pink", "light red", "red"] #(or the hex/rgb equivalent)
Was it helpful?

Solution

Once you've created a Colormap instance, all you need to do is call it with a float value between 0 and 1, and it will return a tuple containing the corresponding RGBA values:

>>> gradient2n(0.5)
(1.0, 0.49803921568627452, 0.49803921568627452, 1.0)

There's no straightforward way of representing arbitrary colors as 'human-readable' names - to represent 8bit color you would need 16,777,216 distinct names! However, you can easily convert the RGBA values to a hex string using matplotlib.colors.rgb2hex.

So your overall function might look like:

from matplotlib.colors import rgb2hex

def colors_at_breaks(cmap, breaks):
    return [rgb2hex(cmap(bb)) for bb in breaks]

For example:

>>> colors_at_breaks(gradient2n, breaks)
['#ffffff', '#ffbfbf', '#ff7f7f', '#ff3f3f', '#ff0000']
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top