how to order seaborn pointplot
Asked Answered
G

1

5

Here's code from kaggle Titanic competition kernel:

grid = sns.FacetGrid(train_df, row='Embarked', size=2.2, aspect=1.6)
grid.map(sns.pointplot, 'Pclass', 'Survived', 'Sex', palette='deep')
grid.add_legend()

It produces wrong plot, the one with reversed colors. I'd like to know how to fix this exact code fragment. I tried adding keyword params to grid.map() call - order=["male", "female"], hue_order=["male", "female"], but then plots become empty.

Grandeur answered 24/10, 2017 at 18:18 Comment(2)
What do you mean by wrong colors? The colors are correct as far as I can see. Please clearly state what you get as output and what you expect and in how far the two differ.Achitophel
Colors were switched in case of Embarked='C' in the original plot.Grandeur
A
9

In the code call to grid.map(sns.pointplot, 'Pclass', 'Survived', 'Sex', palette='deep'), the x category is the Pclass and the hue category is the Sex. Hence you need to add

order = [1,2,3], hue_order=["male", "female"]

Complete example (where I took the titanic that ships with seaborn - what wordplay!):

import seaborn as sns
import matplotlib.pyplot as plt

df = sns.load_dataset("titanic")

grid = sns.FacetGrid(df, row='embarked', size=2.2, aspect=1.6)
grid.map(sns.pointplot, 'pclass', 'survived', 'sex', palette='deep', 
             order=[1,2,3], hue_order=["female","male"])
grid.add_legend()

plt.show()

enter image description here

Note that while hue_order is definitely required, you may leave out the order. While this will throw a warning, the correct order is garantied by the fact that those values are numerical and are hence automatically sorted.

Achitophel answered 24/10, 2017 at 21:18 Comment(3)
When I edited the original kernel on kaggle, I found that I had to use the columns with proper casing, otherwise I got a keyErrorHerbherbaceous
@Herbherbaceous This answer uses the dataset which is distributed with seaborn (sns.load_dataset("titanic")). This differs from other commonly used datasets by different column names and also some columns might be missing.Achitophel
Great answer but I would've +1 only for the punKokanee

© 2022 - 2024 — McMap. All rights reserved.