pythonmatplotlibvisualizationcolormap

How to extract hex color codes from a colormap


From the below branca colormap

import branca

color_map = branca.colormap.linear.PuRd_09.scale(0, 250)

colormap = color_map.to_step(index=[0, 10, 20, 50, 70, 90, 120, 200])

enter image description here

How can I extract hex colours for all the steps(index) from the above Branca colormap?


Solution

  • You can use matplotlib.colors.to_hex on colormap.colors:

    from matplotlib.colors import to_hex
    
    out = [to_hex(c) for c in colormap.colors]
    
    # or
    out = list(map(to_hex, colormap.colors))
    

    Output:

    ['#f7f4f9', '#f0ebf4', '#e3d9eb', '#d0aad2', '#d084bf', '#e44199', '#67001f']