Baadshah
Baadshah

Reputation: 164

How to change the order of bar charts in Python?

I am trying to plot a bar chart of total count (y-axis) vs day of the month (x-axis).

The below shown snippet of code sorts the total count, in descending order from left to right, as seen in the image below:

Python is automatically sorting the chart to show the largest sized bar on the left and the smallest sized bar on right, as shown below:

enter image description here

What I would really like the code to do is to sort the day of the month in ascending order instead of sorting on total count.

May I get some hints on how to go about this?

Here is the piece of code I am using for this:

for g, sub_df in May_DATA.groupby('Plaza_Id'):
    sub_df['Date'].value_counts().plot(kind='bar')
    plt.title(g)
    plt.show()

Upvotes: 1

Views: 488

Answers (1)

Jason
Jason

Reputation: 4546

Provided that the column May_DATA['Data'] are datetimes (you can check the datatypes of your columns using df.info), you can sort that column by dates before your plotting loop. Something like:

for g, sub_df in May_DATA.sort('Date').groupby('Plaza_Id'):
    sub_df['Date'].value_counts().plot(kind='bar')
    plt.title(g)
    plt.show()

If the column May_DATA['Date'] is not a datetime, you'll need to first change it to datetime using May_DATA['Date'] = pd.to_datetime(May_DATA.Date).

Upvotes: 2

Related Questions