Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataFrame Plot: how to sort X axis

Tags:

python

pandas

I am plotting some counts from a field of dataframe (pandas) and I found that the X axis is sorted by the counts (descending order). Instead is it possible to sort by the alphabetical order of the field?

Here is the Python code:

df['cartype'].value_counts().plot(kind='bar')

This sorts by the count but I want to sort by the cartype names. Any solution?

like image 376
kee Avatar asked Jul 21 '26 14:07

kee


1 Answers

One option is to use the function 'sort_index', which sorts Series by index labels, after the call to 'value_counts':

df['cartype'].value_counts().sort_index().plot(kind='bar')
like image 200
migjimen Avatar answered Jul 23 '26 03:07

migjimen



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!