Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Seaborn: 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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading