How to get all color codes from LinearSegmentedColormap?

Viewed 589

I am using seaborn to make a colormap and using the below code:

import seaborn as sns

cmap = sns.color_palette("dark:#034694", as_cmap=True)

Now I want the list of all the color-codes from this cmap, its type is matplotlib.colors.LinearSegmentedColormap. What should I do to get all the color-codes from the variable cmap.

1 Answers

clumsy workaround

The idea is to get more colors than are contained in the colormap and then limit the result to the unique colours.

list(set([cmap(a) for a in np.linspace(0,1,1000)]))

longer answer

looking into the source we can see that LinearSegmentedColormap inherits from Colormap, meaning that the __call__ method of Colormap will be executed when we do something like cmap(0.5).

Looking at this method:

    def __call__(self, X, alpha=None, bytes=False):
        
        [...]
        
        if not self._isinit:
            self._init()

        [...]

        if bytes:
            lut = (self._lut * 255).astype(np.uint8)
        else:
            lut = self._lut.copy()  # Don't let alpha modify original _lut.

        [...]

        rgba = lut[xa]
        if not np.iterable(X):
            # Return a tuple if the input was a scalar
            rgba = tuple(rgba)
        return rgba
[omissions mine]
   

we can see that the lookup table self._lut is initialised by self._init(), stored in lut and optionally scaled.

i could not find when exactly _init() is defined.

in any case, we can call _init() and then access the lookup table:

cmap = sns.color_palette("dark:#034694", as_cmap=True)
cmap._init()

rgbas = cmap._lut

and then convert to hex as pointed out in your comment

hexes = [matplotlib.colors.rgb2hex(x) for x in rgbas]
Related