如何订购 seaborn 点图

how to order seaborn pointplot

这是来自 kaggle 泰坦尼克号竞赛的代码 kernel:

grid = sns.FacetGrid(train_df, row='Embarked', size=2.2, aspect=1.6)
grid.map(sns.pointplot, 'Pclass', 'Survived', 'Sex', palette='deep')
grid.add_legend()

它产生错误的情节,颜色颠倒的情节。我想知道如何修复 这个确切的代码片段 。我尝试将关键字参数添加到 grid.map() 调用 - order=["male", "female"], hue_order=["male", "female"],但随后图变空了。

grid.map(sns.pointplot, 'Pclass', 'Survived', 'Sex', palette='deep') 的代码调用中,x 类别是 Pclass,色调类别是 Sex。因此你需要添加

order = [1,2,3], hue_order=["male", "female"]

完整示例(我使用了 seaborn 附带的泰坦尼克号 - 多么文字游戏!):

import seaborn as sns
import matplotlib.pyplot as plt

df = sns.load_dataset("titanic")

grid = sns.FacetGrid(df, row='embarked', size=2.2, aspect=1.6)
grid.map(sns.pointplot, 'pclass', 'survived', 'sex', palette='deep', 
             order=[1,2,3], hue_order=["female","male"])
grid.add_legend()

plt.show()

请注意,虽然 hue_order 是绝对必需的,但您可以省略 order。虽然这会引发警告,但这些值是数字并因此自动排序的事实保证了正确的顺序。