1
votes

I want to plot facetgrid with seaborn and use 'hue' to identify the number is large or small. However, when I includes 'hue', the number of bars changed.

Generating data

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

If I don't use 'hue', it shows all bars. However, the color_palette is not applied.

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

enter image description here

If I use 'hue', the color is correct but it only shows two bars.

enter image description here

Ideal chart will show all bars and apply the color_palette. Please help and explain it. Thanks!

2

2 Answers

1
votes

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

0
votes

The seaborn.FacetGrid Warning suggests using relplot() or catplot()

Warning

When using seaborn functions that infer semantic mappings from a dataset, care must be taken to synchronize those mappings across facets (e.g., by defing the hue mapping with a palette dict or setting the data type of the variables to category). In most cases, it will be better to use a figure-level function (e.g. relplot() or catplot()) than to use FacetGrid directly.