1

I know how to plot something like this:

               SEASON1  SEASON2  SEASON3
area                                    
A   299.0  2.0  257.0
B   13.0  33.0  198.0
C   22044.0  2.0  22.0

Using

df.plot(kind='bar', stacked=True, rot=90, edgecolor='black')
df.T.plot(kind='bar', stacked=True, rot=0, edgecolor='black')

Resulting in:

stacked

transposed stacked

I'm having hard time to obtain the same (or even better looking) plots for the following df which is representing the original df but made more elegantly here.

1 Answers1

1

What you want to do is to unstack your dataframe, and change the name of the columns.

You can do so by doing :

df.unstack()
  .rename(columns = {
            "2016Q1" : "Season 1",
            "2016Q2" : "Season 2",
            "2016Q3" : "Season 3",
        })

You can find examples on the documentation about what unstack does, and how it is doing it. As for the rename method, it takes a mapping to convert your names from something to something else.

I didn't try to make your example work, but I took an example from the unstack documentation above.

index = pd.MultiIndex.from_tuples([('one', 'a'), ('one', 'b'),
                                   ('two', 'a'), ('two', 'b')])

df = pd.DataFrame( np.arange(1.0, 5.0), index=index, columns=['hi'])
print(df)
#         hi
# one a  1.0
#     b  2.0
# two a  3.0
#     b  4.0

df = df.unstack(level = -1)
       .rename(columns = {
            "a" : "Season 1",
            "b" : "Season 2"
        })
print(df)
#           hi         
#     Season 1 Season 2
# one      1.0      2.0
# two      3.0      4.0

There could be a better way to handle the "hi" above your DataFrame but you can just select it, and it'll disappear.

print( s['hi'] )
     Season 1  Season 2
one       1.0       2.0
two       3.0       4.0
IMCoins
  • 3,149
  • 1
  • 10
  • 25
  • Sweet. Tested. Working! So I'm concluding that the best practice is perhaps is not to deal with the original multi-index `df` right? If so, I will go and mark the answer as accepted. –  Dec 07 '18 at 09:14
  • @KyleDickson Well, I didn't make a lot of research on the subject but thinking about it, usually plots are 2D, and a DataFrame is a 2D object. Multi Index are useful to handle 2D+ data. I don't think pandas multi index handles plots on a 3D level though. I don't think it has to do with best practice or anything there. – IMCoins Dec 07 '18 at 09:18
  • @KyleDickson If you look at [this answer](https://stackoverflow.com/a/25401328/8003790), you can see that you could decide to plot your multi index on different axes. It would just be a different choice. :) Here, you shouldn't be thinking about best practice but possibilities : can I plug a 3D object into a 2D plotter ? :p – IMCoins Dec 07 '18 at 09:20