How can I order the bars in a Seaborn countplot by count?

In order to order the bars in a Seaborn countplot by count, you can use the sort parameter and set it to True. This will sort the bars in the plot in descending order by count. Alternatively, you can also use the order parameter to specify the order in which the bars should be displayed.


You can use the following basic syntax to order the bars in a seaborn countplot in descending order:

sns.countplot(data=df, x='var', order=df['var'].value_counts().index)

To order the bars in ascending order, simply add ascending=True in the value_counts() function:

sns.countplot(data=df, x='var', order=df['var'].value_counts(ascending=True).index)

The following examples show how to use this syntax in practice with the following pandas DataFrame:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'team': ['A', 'A', 'A', 'A', 'B', 'C', 'C', 'C', 'D', 'D'],
                   'points': [12, 11, 18, 15, 14, 20, 25, 24, 32, 30]})

#view DataFrame
print(df)

  team  points
0    A      12
1    A      11
2    A      18
3    A      15
4    B      14
5    C      20
6    C      25
7    C      24
8    D      32
9    D      30

Example 1: Create Seaborn countplot with Bars in Default Order

The following code shows how to create a seaborn countplot in which the bars are in the default order (i.e. the order in which the unique values appear in the column):

import seaborn as sns

#create countplot to visualize occurrences of unique values in 'team' column
sns.countplot(data=df, x='team')

Notice that the bars in the plot are simply ordered based on the order in which the unique values appear in the team column.

Example 2: Create Seaborn countplot with Bars in Descending Order

The following code shows how to create a seaborn countplot in which the bars are in descending order:

import seaborn as sns

#create countplot with values in descending order
sns.countplot(data=df, x='team', order=df['team'].value_counts().index)

seaborn countplot with bars in descending order

Notice that the bars in the plot are now in descending order.

Example 3: Create Seaborn countplot with Bars in Ascending Order

import seaborn as sns

#create countplot with values in ascending order
sns.countplot(data=df, x='team', order=df['team'].value_counts(ascending=True).index)

seaborn countplot with bars in ascending order

Notice that the bars in the plot are now in ascending order.

Note: You can find the complete documentation for the seaborn countplot() function .

x