Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Pandas - Don't sort bar graph on y axis values

Tags:

python

I am beginner in Python. I have a Series with Date and count of some observation as below

Date      Count

2003        10

2005        50

2015        12

2004        12

2003        15

2008        10

2004        05

I wanted to plot a graph to find out the count against the year with a Bar graph (x axis as year and y axis being count). I am using the below code

import pandas as pd

pd.value_counts(sfdf.Date_year).plot(kind='bar')

I am getting the bar graph which is automatically sorted on the count. So I am not able to clearly visualize how the count is distributed over the years. Is there any way we can stop sorting the data on the bar graph on the count and instead sort on the x axis values (i,e year)?

like image 970
Arvind Avatar asked Oct 26 '25 17:10

Arvind


2 Answers

I know this is an old question, but in case someone is still looking for another answer.

I solved this by adding .sort_index(axis=0)

So, instead of this:

pd.value_counts(sfdf.Date_year).plot(kind='bar')

you can write this:

pd.value_counts(sfdf.Date_year).sort_index(axis=0).plot(kind='bar')

Hope, this helps.

like image 86
Ivan Avatar answered Oct 29 '25 07:10

Ivan


The following code uses groupby() to join the multiple instances of the same year together, and then calls sum() on the groupby() object to sum it up. By default groupby() pushes the grouped object to the dataframe index. I think that groupby() automatically sorts, but just in case, sort(axis=0) will sort the index. All that then remains is to plot. All in one line:

df = pd.DataFrame([[2003,10],[2005,50],[2015,12],[2004,12],[2003,15],[2008,10],[2004,5]],columns=['Date','Count'])
df.groupby('Date').sum().sort(axis=0).plot(kind='bar')
like image 33
Dov Grobgeld Avatar answered Oct 29 '25 07:10

Dov Grobgeld



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!