Extract matplotlib colormap in hex-format

For future reference: My CMasher package provides a function called take_cmap_colors() (https://cmasher.readthedocs.io/user/usage.html#taking-colormap-colors), which allows one to take any number of discrete colors from a given colormap and return them in any format (8-bit, normalized or HEX) they want.

So, if you for example wanted to take 5 colors in HEX from the viridis colormap, you could do this with:

import cmasher as cmr

colors = cmr.take_cmap_colors('viridis', 5, return_fmt='hex')

or if you want all colors in HEX from a colormap in a specific value range, you can do that with:

colors = cmr.take_cmap_colors('viridis', None, cmap_range=(0.2, 0.8), return_fmt='hex')

You can get a tuple of rgba values for the segment with index i by calling cmap(i). There is also already a function that turns rgb values into hex. As Joe Kington wrote in the comments, you can use matplotlib.colors.rgb2hex. Therefore, a possible solution would be:

from pylab import *

cmap = cm.get_cmap('seismic', 5)    # PiYG

for i in range(cmap.N):
    rgba = cmap(i)
    # rgb2hex accepts rgb or rgba
    print(matplotlib.colors.rgb2hex(rgba))

The output is:

#00004c
#0000ff
#ffffff
#ff0000
#7f0000