Extract matplotlib colormap in hex-format

33,726

Solution 1

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

Solution 2

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')
Share:
33,726
pir
Author by

pir

Updated on January 12, 2021

Comments

  • pir
    pir over 3 years

    I am trying to extract discrete colors from a matplotlib colormap by manipulating this example. However, I cannot find the N discrete colors that are extracted from the colormap.

    In the code below I've used cmap._segmentdata, but I've found that it is the definition of the entire colormap. Given a colormap and an integer N, how do I extract N discrete colors from the colormap and export them in hex-format?

    from pylab import *
    
    delta = 0.01
    x = arange(-3.0, 3.0, delta)
    y = arange(-3.0, 3.0, delta)
    X,Y = meshgrid(x, y)
    Z1 = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
    Z2 = bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
    Z = Z2 - Z1 # difference of Gaussians
    
    cmap = cm.get_cmap('seismic', 5)    # PiYG
    cmap_colors = cmap._segmentdata
    
    def print_hex(r,b,g):
                   if not(0 <= r <= 255 or 0 <= b <= 255 or 0 <= g <= 255):
                                  raise ValueError('rgb not in range(256)')
                   print '#%02x%02x%02x' % (r, b, g)
    
    
    for i in range(len(cmap_colors['blue'])):
                   r = int(cmap_colors['red'][i][2]*255)
                   b = int(cmap_colors['blue'][i][2]*255)
                   g = int(cmap_colors['green'][i][2]*255)
                   print_hex(r, g, b)
    
    
    
    im = imshow(Z, cmap=cmap, interpolation='bilinear',
                vmax=abs(Z).max(), vmin=-abs(Z).max())
    axis('off')
    colorbar()
    
    show()
    
  • alexmloveless
    alexmloveless over 3 years
    or using list comprehension [matplotlib.colors.rgb2hex(c) for c in cmap.colors]