本文介绍了Seaborn FacetGrid中的Hue参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 Facetgrid 时遇到问题:当我使用 hue 参数时,x 标签以错误的顺序显示并且与数据不匹配.在 ipython 中加载 Titanic 数据集:

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和Hue:

Facetgrid with Hue:

由此看来,女性比男性多,但这不是事实.

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

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

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:

Facetgrid without Hue:

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

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

推荐答案

如果您打算将 FacetGrid 与分类绘图函数之一一起使用,则需要通过声明类别变量或具有 order hue_order 参数的变量:

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])

但是,通常最好使用 factorplot ,它可以帮助您完成簿记工作,并且还可以节省一些键入时间:

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

这篇关于Seaborn FacetGrid中的Hue参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-30 21:02