Home > OS >  convert ColorMap to list
convert ColorMap to list

Time:12-12

If I run

import seaborn as sns

list(sns.diverging_palette(230, 20, as_cmap=False))

then I get

[(0.2509335357076959, 0.4944143311197457, 0.6104170295454565),
 (0.5266567751883763, 0.6751928585334119, 0.7467240840661897),
 (0.8050726244296104, 0.8577368012538521, 0.884362262166227),
 (0.9140860646530862, 0.8246826885128927, 0.8028133239419792),
 (0.8384144678873866, 0.5785740917778832, 0.5129511551488873),
 (0.7634747047461135, 0.3348456555528834, 0.225892295531744)]

However, if I do

list(sns.diverging_palette(230, 20, as_cmap=True))

then I get an error:

TypeError: 'LinearSegmentedColormap' object is not iterable

Is there a way to convert a Colormap to a list, like I could do above when I passed as_cmap=False?

Here's what I would like to end up with:

def func(cmap):
    ...

cmap = sns.diverging_palette(230, 20, as_cmap=True)
func(cmap)

returning a list like the one above.

How can I write such a func?

CodePudding user response:

Internally, a matplotlib colormap is just a list of 256 colors. Externally, it is a function that maps a number between 0 and 1 to one of these colors. So you can call the colormap with an array of 256 equally-spaced points between 0 and 1 to get the list:

import seaborn as sns
import numpy as np

cmap_as_list1 = sns.diverging_palette(230, 20, as_cmap=True)(np.linspace(0, 1, 256))
sns.palplot(cmap_as_list1)

list of 256 colors

Seaborn stores its palettes just as lists of colors, so you can use as_cmap=False and ask n=256 colors:

cmap_as_list2 = sns.diverging_palette(230, 20, n=256, as_cmap=False)
sns.palplot(cmap_as_list2)

a seaborn palette with 256 colors

  • Related