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

3
  • 1
    Does this answer your question? sorting by a custom list in pandas Commented Mar 25, 2020 at 22:37
  • @Alan No, actually. It didn't work. I am trying to see if pandas dataframe plot can do the custom sort. Commented Mar 25, 2020 at 23:01
  • Please, provide the data you are working with. Thanks. Commented Mar 26, 2020 at 0:22

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.