pythonpandasseabornbar-charthue

How to set the hue order in Seaborn plots


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:

barplot by categories

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


Solution

  • 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")