lgd
lgd

Reputation: 1462

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.

Upvotes: 4

Views: 7384

Answers (2)

mwaskom
mwaskom

Reputation: 49002

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"].

Upvotes: 6

James
James

Reputation: 335

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:]
    )
    

Upvotes: 4

Related Questions