Set order on sns histplot

Viewed 6719

I'm trying to set the order of a stacked histplot using seaborn. Below, then plot is fine but I'm hoping to alter the order so it reads Up, Down, Left, Right when reading left to right.

I get an error when trying to pass order or col_order.

raise AttributeError('{!r} object has no property {!r}'

AttributeError: 'Rectangle' object has no property 'order'

It works fine when not passing the order though.

import pandas as pd
import seaborn as sns

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

g = sns.histplot(data = df, 
            x = 'Item', 
            hue = 'Label',
            #order = ['Up','Down','Left','Right'],
            multiple = 'fill', 
            shrink = 0.8, 
            discrete = True,
            legend = True,
            )
1 Answers

You cannot order it from within seaborn. You could order it from pandas though. To provide a custom sorting order for strings, you can turn the Item column into a Categorical, and specify the order in the second parameter.

After that, you will get the plot ordered as you want:

df['Item'] = pd.Categorical(df['Item'], ['Up','Down','Left','Right'])

The full code:

import pandas as pd
import seaborn as sns

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


df['Item'] = pd.Categorical(df['Item'], ['Up','Down','Left','Right'])

g = sns.histplot(data = df, 
            x = 'Item', 
            hue = 'Label',
            #order = ['Up','Down','Left','Right'],
            multiple = 'fill', 
            shrink = 0.8, 
            discrete = True,
            legend = True,
            )
Related