首页 > 解决方案 > Seaborn FacetGrid 'hue' 改变了条数

问题描述

我想用 seaborn 绘制 facetgrid 并使用“hue”来识别数字的大小。但是,当我包含“色调”时,条数发生了变化。

生成数据

import pandas as pd
import numpy as np
import seaborn as sns

np.random.seed(0)

groups = ('Group 1', 'Group 2')
means = ('Low', 'High', 'Mid')
index =  pd.MultiIndex.from_product(
    [groups, means], 
   names=['Group', 'Mean']
)
values = np.random.randint(low=20, high=100, size=len(index))
data = pd.DataFrame(data={'val': values}, index=index).reset_index()
data['is_positive'] = data['val'] > 75
    Group   Mean    val is_positive
0   Group 1 Low     64  False
1   Group 1 High    67  False
2   Group 1 Mid     84  True
3   Group 2 Low     87  True
4   Group 2 High    87  True
5   Group 2 Mid     29  False

如果我不使用“色调”,它会显示所有条形。但是,color_palette不适用。

colors = ["red", "green"]
customPalette = sns.set_palette(sns.color_palette(colors))
g = sns.FacetGrid(data, col="Group", hue='is_positive', height=3, col_wrap=6, palette=customPalette)
g.map(sns.barplot, 'val', 'Mean')

在此处输入图像描述

如果我使用“色调”,颜色是正确的,但它只显示两个条。

在此处输入图像描述

理想的图表将显示所有条形并应用 color_palette。请帮忙解释一下。谢谢!

标签: pandasseaborn

解决方案


I think you need to pass order option to barplot:

g = sns.FacetGrid(df, col="Group", height=3, hue='is_positive', 
                  col_wrap=6, palette=customPalette)
g.map(sns.barplot, 'val', 'Mean', order=['Low','Mid','High'])

Output:

enter image description here


推荐阅读