Seaborn countplot: How to Order Bars by Count


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

The following code shows how to create a seaborn countplot in which the bars are 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 here.

Additional Resources

The following tutorials explain how to perform other common functions in seaborn:

How to Plot a Distribution in Seaborn
How to Order Boxplots on x-axis in Seaborn
How to Add a Table to Seaborn Plot

Leave a Reply

Your email address will not be published. Required fields are marked *