ShanZhengYang
ShanZhengYang

Reputation: 17621

How to switch the colors of two categories in seaborn?

Let's say I use the following 'iris' example with scatterplots

import pandas as pd
import seaborn as sns
sns.set(style="whitegrid", palette="muted")

# Load the example iris dataset
iris = sns.load_dataset("iris")

# "Melt" the dataset to "long-form" or "tidy" representation
iris = pd.melt(iris, "species", var_name="measurement")

# Draw a categorical scatterplot to show each observation
sns.swarmplot(x="measurement", y="value", hue="species", data=iris)

which outputs the following plot:

enter image description here

But let's say I wanted to switch the colors between setosa and versicolor, making setosa green and versicolor blue, explicitly using the seaborn palette. I would try something like this:

sns.set(style="whitegrid", palette="muted")
iris = sns.load_dataset("iris")
iris = pd.melt(iris, "species", var_name="measurement")
sns.swarmplot(x="measurement", y="value", hue="species", data=iris, palette=dict(setosa = 'g', versicolor = 'b', virginica = 'r'))

Naturally, this doesn't work:

enter image description here

The color palette is now off.

(1) How do you switch two categories keeping seaborn's colour palette?

(2) What is you wanted to chose another seaborn "standard" color, like cyan? How could I switch setosa from blue to cyan?

Upvotes: 3

Views: 11935

Answers (1)

Merlin
Merlin

Reputation: 25629

Seaborn is opensource: The hexcodes are listed here: https://github.com/mwaskom/seaborn/blob/master/seaborn/palettes.py

SEABORN_PALETTES = dict(
    deep=["#4C72B0", "#55A868", "#C44E52",
          "#8172B2", "#CCB974", "#64B5CD"],
    muted=["#4878CF", "#6ACC65", "#D65F5F",
           "#B47CC7", "#C4AD66", "#77BEDB"],
    pastel=["#92C6FF", "#97F0AA", "#FF9F9A",
            "#D0BBFF", "#FFFEA3", "#B0E0E6"],
    bright=["#003FFF", "#03ED3A", "#E8000B",
            "#8A2BE2", "#FFC400", "#00D7FF"],
    dark=["#001C7F", "#017517", "#8C0900",
          "#7600A1", "#B8860B", "#006374"],
    colorblind=["#0072B2", "#009E73", "#D55E00",
                "#CC79A7", "#F0E442", "#56B4E9"]
    )


sns.set(style="whitegrid", palette="muted")
iris     = sns.load_dataset("iris")
iris     = pd.melt(iris, "species", var_name="measurement")
muted    = ["#4878CF", "#6ACC65", "#D65F5F", "#B47CC7", "#C4AD66", "#77BEDB"]
newPal   = dict(setosa = muted[0], versicolor = muted[2], virginica = muted[1])
sns.swarmplot(x="measurement", y="value", hue="species", data=iris,palette=newPal )

enter image description here

Upvotes: 5

Related Questions