Reputation: 2158
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()
Looking for this output
Upvotes: 0
Views: 1339
Reputation: 150735
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:
Upvotes: 1