pandasmatplotlibseaborncountplot

Sorting countplot by ascending


How, can I sort this plot to show from biggest to lowest? I tried to use sort_values but does not work

plt.figure(figsize=(15,8))
sns.countplot(x='arrival_date_month',data=df.sort_values('arrival_date_month',ascending=False))
plt.xticks(rotation=45)

enter image description here


Solution

  • The default ordering for a column of type string is the order of occurrence in the dataframe.

    You can set a fixed order, either by using the order= keyword, or by making the column Categorical.

    To order from low to high, you can use pandas df.groupby('...').size().sort_values().index for the order= parameter. Use ...[::-1] to reverse that order.

    Here is some example code:

    import matplotlib.pyplot as plt
    import seaborn as sns
    import pandas as pd
    import numpy as np
    
    np.random.seed(2021)
    sns.set()
    month_names = ['January', 'February', 'March', 'April', 'May', 'June',
                   'July', 'August', 'September', 'October', 'November', 'December']
    df = pd.DataFrame({'arrival_date_month': np.random.choice(month_names, 1000)})
    
    fig, axs = plt.subplots(ncols=3, figsize=(16, 3))
    
    sns.countplot(x='arrival_date_month', data=df, ax=axs[0])
    axs[0].set_title('default order (order of occurrence)')
    
    sns.countplot(x='arrival_date_month', data=df, order=month_names, ax=axs[1])
    axs[1].set_title('setting an explicit order')
    
    large_to_small = df.groupby('arrival_date_month').size().sort_values().index[::-1]
    sns.countplot(x='arrival_date_month', data=df, order=large_to_small, ax=axs[2])
    axs[2].set_title('order from largest to smallest')
    
    for ax in axs:
        ax.tick_params(axis='x', rotation=45)
    plt.tight_layout()
    plt.show()
    

    ordering sns.countplot from high to low