Search code examples
pythonseabornfacet-grid

Facetgrid to plot stacked normalised counts - Seaborn


I'm aiming to use Seaborn facet grid to plot counts of values but normalised, rather than pure counts. Using below, each row should display each unique value in Item. The x-axis should display Num and the values come from Label.

However, each row isn't being partitioned. The same data is displayed for each Item.

import pandas as pd
import Seaborn as sns

df = pd.DataFrame({      
    'Num' : [1,2,1,2,3,2,1,3,2],
    'Label' : ['A','B','C','B','A','C','C','A','B'],   
    'Item' : ['Up','Left','Up','Left','Down','Right','Up','Down','Right'],      
    })

g = sns.FacetGrid(df, 
              row = 'Item', 
              row_order = ['Up','Right','Down','Left'],                           
              aspect = 2, 
              height = 4, 
              sharex = True,
              legend_out = True
              )

g.map(sns.histplot, x = 'Num', hue = 'Label', data = df, multiple = 'fill', shrink=.8) 
g.add_legend()

Solution

  • Maybe you can try g.map_dataframe(sns.histplot, x='Num', hue = 'Label', multiple = 'fill', shrink=.8). I'm not good at seaborn, I just look it up at https://seaborn.pydata.org/generated/seaborn.FacetGrid.html and map_dataframe seems work better than map.