问题
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:
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:
What's going on here? I am using Seaborn 0.7.0
回答1:
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])
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")
来源:https://stackoverflow.com/questions/36863342/hue-parameter-in-seaborn-facetgrid