0

I am trying to sort categorical variables in the pandas plot x axis. I tried sorting from pandas dataframe itself but I can only sort it alphabetically. I don't see options in plot to sort it this way. I am trying to get x axis in this order: [Mon, Tue, Wed, Thru, Fri, Sat, Sun] . How do I do that?

df = data_df.groupby(['name1','weekday']).sum().reset_index()
s = (df.pivot_table(
        index='weekday', columns='name1', values='count', aggfunc='sum'))

s.plot(kind='bar', stacked=True,figsize=(20,10),rot=0)
plt.show()

enter image description here

Looking for this output

sharp
  • 2,140
  • 9
  • 43
  • 80
  • 1
    Does this answer your question? [sorting by a custom list in pandas](https://stackoverflow.com/questions/23482668/sorting-by-a-custom-list-in-pandas) – Alan Mar 25 '20 at 22:37
  • @Alan No, actually. It didn't work. I am trying to see if pandas dataframe plot can do the custom sort. – sharp Mar 25 '20 at 23:01
  • Please, provide the data you are working with. Thanks. – sentence Mar 26 '20 at 00:22

1 Answers1

1

As far as I can see, your df and s are essentially the same. Also, you can reindex and then plot:

weekdays = ['Monday','Tuesday','Wednesday','Thursday',
            'Friday','Saturday','Sunday']
# sample data
np.random.seed(1)
data_df = pd.DataFrame({
    'name1':np.random.randint(0,3, 100),
    'weekday':np.random.choice(weekdays, 100),
    'count':np.random.randint(3,100)
})

# groupby and take sum
s = (data_df.groupby(['name1','weekday'])
       .sum().unstack('name1')
       .reindex(weekdays)                 # here is the key to get the correct order
)

# plot
s.plot.bar(stacked=True)

Output:

enter image description here

Quang Hoang
  • 146,074
  • 10
  • 56
  • 74