pythonseaborncountplot

How to set the countplot order


I am trying to determine the order of my countplot. This is the code I wrote:

df['new salery'].sort_values()
sns.set(rc={'figure.figsize':(8,6)})
sns.countplot(x='new salery',data=df,palette='viridis')

the plot I got is: CountPlot

What I am trying to do is to put this order -

Low salary, Medium Salary -, Medium Salary, Medium Salary +, High Salary.


Solution

  • I would make the column an ordered Categorical. From this, seaborn automatically follows the order:

    df['new salery'] = pd.Categorical(df['new salery'], 
      categories=['light', 'medium-', 'medium', 'medium+', 'large'], ordered=True)
    sns.countplot(x='new salery', data=df, palette='viridis')
    

    Alternatively, if you only want to do it for the plot, you can also use the order-keyword within the function:

    sns.countplot(x='new salery',data=df,palette='viridis', 
                  order=['light', 'medium-', 'medium', 'medium+', 'large'])
    

    Ordered countplot