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

Time:01-24

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

CodePudding user response:

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:])

CodePudding user response:

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');
  • Related