Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to change assignment of colors to labels from palette in python Seaborn?

how can you change the order of colors used by seaborn? example:

import seaborn as sns
import pandas
data = pandas.DataFrame({"x": [1,2,3], "y": [1,1,1], "color": ["a", "b", "c"]})
sns.pointplot(x="x", y="y", hue="color", data=data)

how can the assignment of colors from the default palette, in "hue" be changed? for example, rather than having (blue, green, red) from the palette, having (green, blue, red)? I want to keep the same palette, just change the order of colors.

like image 772
lgd Avatar asked Oct 26 '25 20:10

lgd


2 Answers

pointplot accepts a dictionary with the level names in the keys and color names in the values, so you could do that. In other words, palette=dict(a="g", b="b", c="r"). That is safest, but if you know the order of hues you're going to get (or specify it), you can also do palette=["g", "b", "r"].

like image 157
mwaskom Avatar answered Oct 28 '25 09:10

mwaskom


The Seaborn docs on palettes dance around this, but here's how it works:

  • First, note that color_palette() will return your current color palette.
  • Second, do the example from the docs and assign the current palette to some variable as current_palette = sns.color_palette().
  • Third, note that that object supports __get_item__, so you could get the first and second colors in it as

    first = current_palette[0]
    second = current_palette[1]
    
  • Fourth: note the set_palette() function, which the docs note will accept a list of RGB tuples.

  • Finally, make a new palette as

    sns.set_palette(
        [second, first] + current_palette[2:]
    )
    
like image 43
James Avatar answered Oct 28 '25 10:10

James