0

I am trying to order my bar chart from Jan-Dec instead of highest count of lowest, I'm sure there is an easy fix but I cannot find it. Currently, my graph is ordering itself on the values and not the months on the x-axis. The first line of code I added a month column. The second I found the counts of each month. The third I plot in bar chart.

df1['Month Added'] = pd.DatetimeIndex(df1['Date Added']).month_name()
df_month = df1['Month Added'].value_counts()
df_month.plot(kind='bar')

Output is enter image description here

I tried the following but no luck.

df_month.Month.value_counts().loc[['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']].plot(kind='bar')

Starbucks
  • 135
  • 7
  • 1
    I think this answer may be useful: [link](https://stackoverflow.com/questions/47523483/re-order-dataframe-based-on-month-not-alphabet) – FrancecoMartino Jan 26 '21 at 01:01

1 Answers1

2

Use pandas.Series.sort_index with key and pandas.to_datetime:

df_month = df_month.sort_index(key=lambda x: pd.to_datetime(x, format="%B"))
print(df_month)

Output:

January      25
February     21
March        14
April         5
May          30
June         16
July          8
August       30
September     6
October       9
November     36
December     24
dtype: int64

Then plot:

df_month.plot(kind="bar")

Output:

enter image description here

Chris
  • 29,127
  • 3
  • 28
  • 51