Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the hue order in Seaborn plots

I am new to Seaborn and this is probably a very trivial question, however I'm struggling with the solution. I have a Pandas dataset named titanic I am plotting a bar chart as described in the Seaborn official documentation, using the following code:

import seaborn as sns

titanic = sns.load_dataset("titanic")
sns.catplot(x="sex", y="survived", hue="class", kind="bar", data=titanic)

This produces the following plot:

enter image description here

As you can see, the hue is represented by the class. Question is: How can I manually choose the hue order so that I can reverse the current one?

like image 771
Marioanzas Avatar asked Dec 04 '20 16:12

Marioanzas


People also ask

What is hue order in Seaborn?

In seaborn, the hue parameter represents which column in the data frame, you want to use for color encoding. The example shown here is from the official document for lmplot: import seaborn as sns; sns.set(color_codes=True) tips = sns.load_dataset("tips") g = sns.lmplot(x="total_bill", y="tip", data=tips)

What is hue order?

There is a natural order of hues: red, yellow, green, blue, purple. One can mix paints of adjacent colors in this series and obtain a continuous variation from one to the other. For example, red and yellow may be mixed in any proportion to obtain all the hues red through orange to yellow.

What is the significance of hue parameter in Seaborn plotting?

In seaborn, the hue parameter determines which column in the data frame should be used for colour encoding. Using the official document for lmplot provided an example for this. Adding `hue="smoker" tells seaborn you want to colour the data points for smoker and non-smoker differently.


1 Answers

In order to manually select the hue order of a Seaborn plot, you have to define the desired order as a list and then pass it to the plot function as the argument hue_order . The following code would work:

import seaborn as sns

titanic = sns.load_dataset("titanic")
hue_order = ['Third', 'Second', 'First']
sns.catplot(x="sex", y="survived", hue="class", data=titanic, hue_order=hue_order, kind="bar")
like image 164
Marioanzas Avatar answered Sep 23 '22 05:09

Marioanzas