Search code examples
seabornbar-charthuefacet-grid

Plot does not highlight all the unique values of a column represented by hue


My dataframe has a column 'rideable_type' which has 3 unique values: 1.classic_bike 2.docked_bike 3.electric_bike

While plotting a barplot using the following code:

g = sns.FacetGrid(electric_casual_type_week, col='member_casual', hue='rideable_type', height=7, aspect=0.65)
g.map(sns.barplot, 'day_of_week', 'number_of_rides').add_legend()

I only get a plot showing 2 unique 'rideable_type' values.

Here is the plot:

enter image description here

As you can see only 'electric_bike' and 'classic_bike' are seen and not 'docked_bike'.


Solution

  • The main problem is that all the bars are drawn on top of each other. Seaborn's barplots don't easily support stacked bars. Also, this way of creating the barplot doesn't support the default "dodging" (barplot is called separately for each hue value, while it would be needed to call it in one go for dodging to work).

    Therefore, the recommended way is to use catplot, a special version of FacetGrid for categorical plots.

    g = sns.catplot(kind='bar', data=electric_casual_type_week, x='day_of_week', y='number_of_rides',
                    col='member_casual', hue='rideable_type', height=7, aspect=0.65)
    

    Here is an example using Seaborn's 'tips' dataset:

    import seaborn as sns
    
    tips = sns.load_dataset('tips')
    
    g = sns.FacetGrid(data=tips, col='time', hue='sex', height=7, aspect=0.65)
    g.map_dataframe(sns.barplot, x='day', y='total_bill')
    g.add_legend()
    

    sns.FacetGrid with sns.barplot

    When comparing with sns.catplot, the coinciding bars are clear:

    g = sns.catplot(kind='bar', data=tips, x='day', y='total_bill', col='time', hue='sex', height=7, aspect=0.65)
    

    sns.catplot kind='bar'