menu

Questions & Answers

How to order Months in a categorical order in python, ie Jan, Feb, Mar etc...?

I'm creating a bar chart which has 'Months' on the x axis, however they are displayed in a random order, how do I order the months logically, ie Jan, Feb, Mar...

Here is my code...

    plt.figure(figsize=(15,10))
    sns.countplot(x=boeing_df.order_month);
    plt.title('Most Popular Order Month');ype here

TIA

Comments:
2023-01-24 00:30:12
Hi Rebecca and welcom to SO. It will be great if you can have a look at How to Ask and then try to produce a minimal reproducible example.
Answers(2) :

You can use the order parameter of countplot and give it your list of months. A convenience might be to use calendar.month_abbr:

import calendar
sns.countplot(x=boeing_df.order_month, order=calendar.month_abbr[1:])

You can order the months on the x-axis by reordering the dataframe column 'order_month' using the .sort_values() function in pandas. You can also use the .dt.month attribute to extract the month from the datetime values of the column. Here is an example of how you can reorder the months in your dataframe:

boeing_df = boeing_df.sort_values(by=['order_month'], axis=0)

and to extract the month:

boeing_df['order_month'] = boeing_df['order_month'].dt.month

then use the reordered dataframe to create the countplot.

plt.figure(figsize=(15,10))
sns.countplot(x=boeing_df.order_month);
plt.title('Most Popular Order Month');