1

I have a dataframe that looks like this:

Category    counts  Decade
0   1.0 55  80s
1   2.0 27  80s
2   3.0 13  80s
3   4.0 7   80s
4   5.0 4   80s
0   1.0 55  90s
1   2.0 31  90s
2   3.0 8   90s
3   5.0 7   90s
4   4.0 3   90s
0   1.0 84  00s
1   2.0 35  00s
2   3.0 10  00s
3   4.0 6   00s
4   5.0 1   00s
0   1.0 137 10s
1   2.0 32  10s
2   3.0 13  10s
3   4.0 12  10s
4   5.0 1   10s

I then plot it as a stacked bar chart:

df.pivot_table('counts', 'Decade', 'Category', 'first').plot.bar(stacked=True)

However, this organizes my bars not in chronological order. I realize they are strings, but I figured it would plot the bars from top to bottom in the order of the dataframe. How can I force the plot to start at 80s and increase by decade to the right?

enter image description here

1 Answer 1

2

The pivot_table results in a sorted Index, so you can reindex after the pivot to ensure the correct plotting order.

(df.pivot_table('counts', 'Decade', 'Category', 'first')
   .reindex(['80s', '90s', '00s', '10s'])
   .plot.bar(stacked=True, figsize=(4,3))

enter image description here


Another option, you could enforce a custom ordering using a CategoricalDtype:

import pandas as pd

my_cat = pd.CategoricalDtype(categories=['80s', '90s', '00s', '10s'], ordered=True)
df['Decade'] = df['Decade'].astype(my_cat)

So now when you pivot it will be ordered properly for plotting without the reindex

df.pivot_table('counts', 'Decade', 'Category', 'first')

#Category  1.0  2.0  3.0  4.0  5.0
#Decade                           
#80s        55   27   13    7    4
#90s        55   31    8    3    7
#00s        84   35   10    6    1
#10s       137   32   13   12    1
Sign up to request clarification or add additional context in comments.

1 Comment

Sweet, I didn't realize that's what was occurring.

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.