seaborn FacetGrid 中的 Hue 参数

Hue parameter in seaborn FacetGrid

我在使用 Facetgrid 时遇到问题:当我使用 hue 参数时,x 标签的显示顺序错误和数据不匹配。在 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:

由此看来女性多于男性,其实不然

如果我现在删除 hue 选项,那么我会得到正确的分布:所有 pclasses 中男性多于女性。

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

没有色调的 Facetgrid:

这是怎么回事? 我正在使用 Seaborn 0.7.0

如果要将 FacetGrid 与分类绘图函数之一一起使用,则需要通过将变量声明为分类变量或使用 order 和 [=14 来提供顺序信息=]参数:

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

但是,通常最好使用 factorplot,它会为您进行簿记并节省您的输入时间:

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