seaborn.catplot()色调无法正常工作

2024-04-29 07:55:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试用seaborn.catplot替换seaborn.facetgrid。但是seaborn.catplot没有正确标记Embarked = C面中的色调

数据集:泰坦尼克号


e = sns.FacetGrid(data= train_df, col='Embarked')
e.map_dataframe(sns.pointplot, 'Pclass', 'Survived', hue='Sex', palette='deep')
e.add_legend()

at Embarked C male is properly presented as hue

C:男性正确地呈现为色调


但是我的seaborn.catplot显示:

sns.catplot(x='Pclass', y= 'Survived', hue='Sex', data=train_df, kind='point',  col='Embarked')

in Emabarked= C male is not properly hued

C男性未正确呈现为色调


Tags: dfdatatraincolseaborn色调huesns
2条回答

谢谢你,约翰。是的,我的计划错了。我手动检查过了

train_df[(train_df['Embarked']=='C') & (train_df['Survived']==1)].groupby('Sex').count()['Survived']

输出:

Sex
    female    64
    male      29

雌性比雄性大。 在FacetGridhue_order应该指定,否则可能会给出错误的结果

约翰在评论中已经对答案进行了嘲弄。我只想解释和完成

以下是seaborn.catplotdocumentation关于排序的说明:

As in the case with the underlying plot functions, if variables have a categorical data type, the levels of the categorical variables, and their order will be inferred from the objects. Otherwise you may have to use alter the dataframe sorting or use the function parameters (orient, order, hue_order, etc.) to set up the plot correctly.

这意味着您可以使用hue_order参数来确保绘图的顺序符合您的要求:

order, hue_order: lists of strings, optional
Order to plot the categorical levels in, otherwise the levels are inferred from the data objects.

以下是如何在您的案例中使用它:

sns.catplot(x='Pclass', y='Survived', hue='Sex', hue_order=['male', 'female'], data=train_df, kind='point', col='Embarked')

或者,正如文档中所描述并由JohanC指出的,您可以将列train_df['Sex']的类型转换为分类类型。然后通过seaborn推断顺序

相关问题 更多 >