Hue parameter in seaborn FacetGrid

2020-05-27 07:52发布

I am having a problem with Facetgrid: when I use the hue parameter, the x-labels show up in the wrong order and do not match the data. Loading the Titanic dataset in ipython:

%matplotlib inline
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

titanic = sns.load_dataset("titanic")
g = sns.FacetGrid(titanic, col='pclass', hue='survived')
g = g.map(sns.swarmplot, 'sex', 'age')

Facetgrid with Hue: Facetgrid with Hue

From this it seems that there are more females than males, but this is not true.

If I now remove the hue option, then I get a correct distribution: there are more males than females across all pclasses.

g = sns.FacetGrid(titanic, col='pclass')
g = g.map(sns.swarmplot, 'sex', 'age')

Facetgrid without Hue: Facetgrid without Hue

What's going on here? I am using Seaborn 0.7.0

1条回答
一纸荒年 Trace。
2楼-- · 2020-05-27 08:13

If you are going to use FacetGrid with one of the categorical plotting functions, you need to supply order information, either by declaring the variables as categorical or with the order and hue_order parameters:

g = sns.FacetGrid(titanic, col='pclass', hue='survived')
g = g.map(sns.swarmplot, 'sex', 'age', order=["male", "female"], hue_order=[0, 1])

enter image description here

However, it is generally preferable to use factorplot, which will take care of this bookkeeping for you and also save you some typing:

g = sns.factorplot("sex", "age", "survived", col="pclass", data=titanic, kind="swarm")

enter image description here

查看更多
登录 后发表回答