41

Seaborn has an option to create nice color palettes. I wish to use these palettes to generate colors that work well together in a map where countries are shaded according to some property. The following code produces 8 shades of purple from light to dark. Note also the ability to specify the number of colors is required so I cannot just use a fixed palette of defined colors.

import seaborn as sns
num_shades = 8
sns.palplot(sns.cubehelix_palette(num_shades))

If I run the same but in a list like so:

color_list = sns.cubehelix_palette(num_shades)

you get:

[[0.9312692223325372, 0.8201921796082118, 0.7971480974663592], ... 

These are clearly not RGB values which is what I need.

1) What format are these colors in? 2) How can I convert to RGB or 6 digit codes?

I have tried searching for quite some time and found no answers. I have looked here and at other seaborn documentation:

https://stanford.edu/~mwaskom/software/seaborn/generated/seaborn.set_color_codes.html

I can convert to 6 digit codes from RGB using:

Converting a RGB color tuple to a six digit code, in Python

but am stuck as to how to do it direct or via getting the RGB values. Any help would be appreciated.

Community
  • 1
  • 1
Pete
  • 767
  • 3
  • 9
  • 16

3 Answers3

91

If by "6 digit code" you mean a hex code, you can also do:

pal = sns.color_palette(...)
pal.as_hex()
mwaskom
  • 46,693
  • 16
  • 125
  • 127
  • 1
    Works! It returns a list of strings with the # added. See: `import seaborn; pal_hls = seaborn.hls_palette(12, l=.3, s=.8).as_hex(); print(pal_hls);` – Iacchus Oct 24 '16 at 02:48
  • 1
    Thank you very much! That's exactly what I needed. – Leda Grasiele Jan 15 '20 at 18:25
  • 5
    This should be the accepted answer. The current accepted answer works, but it manually reinvents the wheel instead of using an existing built-in function – Niema Moshiri Jan 31 '20 at 18:26
11

The values you are getting are percentages of 255, the max RGB value. Just multiply each triplet of values by 255 (and round off, if you like) to get the RGB values.

for color in color_list:
    for value in color:
        value *= 255

Then store those in a new list to have your list of RGB values.

perfect5th
  • 1,992
  • 1
  • 17
  • 18
3

Just adding a point to @mwaskom answer as I am not allowed to comment yet.

pal = sns.color_palette(...)
pal.as_hex()

This in my case was giving colors as shown in the image1 (using python 3.9), image1

If you want color hex codes, you can slice it like this:

pal = sns.color_palette(...)
pal.as_hex()[:]

For a particular color, say the first color, use this:

pal = sns.color_palette(...)
pal.as_hex()[0]
Iftikhar Ud Din
  • 341
  • 3
  • 5