Ali
Ali

Reputation: 837

Sorting categorical labels in seaborn chart

I'm sure this should be easy, but I can't find in the seaborn documentation how I specifically choose the order of my x label categorical variables which are to be displayed?

I have hours worked per week as follows below, but I want to order these on my x axis from 0-10, 11-20, 21-30, 31-40 and More than 40 hours. How can I do this?

def hours_per_week (x):
if x < 11: return '0-10 hours'
elif x < 21: return '11-20 hours'
elif x < 31: return '21-30 hours'
elif x < 41: return '31-40 hours'
else: return 'More than 40 hours'

This is my seaborn code to plot the chart. Note 'income-cat' is a categorical grouping of people earning under 50K and those earning above 50K

plot_income_cat_hours = sns.countplot(x='hours_per_week_grouping',
                                      hue='income-cat', data=data)

This is currently how my plot looks (with some additional formatting not included in the code above because not relevant): enter image description here

Upvotes: 16

Views: 28880

Answers (2)

Amit Wolfenfeld
Amit Wolfenfeld

Reputation: 623

Set the order parameter.

plot_income_cat_hours = sns.countplot(x='hours_per_week_grouping',
                        hue='income-cat', data=data, order=['place the desired order here'])

Upvotes: 32

BEATHUB
BEATHUB

Reputation: 79

You may try the following,

sns.countplot(data = data.sort_values(by="hours_per_week_grouping"), 
              x= "hours_per_week_grouping", hue= "income-cat")

Upvotes: 2

Related Questions