Plot Specific Column from Multindex Table with Pandas

Viewed 33

I have create tabale using aggregation in pandas that looks like this:

df=df.groupby(['choice mode','required like me']).agg({'mean prop like me ':['mean'],'unhappy':['mean']})

>>>                         mplm          unhappy
choice mode         rlm     mean         mean
ba                  0.2     0.651        11
                    0.3     0.561        12
                    0.6     0.721        10
btc                 0.2     0.891        0
                    0.3     0.124        0
                    0.6     0.321        0
btr                 0.2     0.412        12
                    0.3     0.112        34
                    0.6     0.531        31

The table is multindex table. I would like to create two charts: chart one: x_axis= rlm, y_axis=mplm mean , with three lines- one line per choice mode chart two: x_axis= rlm, y_axis=unhappy mean , with three lines- one line per choice mode

The problem is that I am not able to sepeerate between the unhappy and mplm :

df.unstack(level=0).plot()

enter image description here

as you can see I get 6 lines and the plot has all the levels of the indices.

I want to get two different charts with values of plm ot unhappy values.

I could do it by slicing the original table to have onlu plm or unhappy and then to do the aggregation and to drop level, but I'm sure there is smarter way to do that

1 Answers

You can unstack the dataframe on level=0, then select the multiindex column which you would like to plot:

s = df.unstack(level=0)
s[('mplm', 'mean')].plot(), s[('unhappy', 'mean')].plot()

Optionally, you can drop the unused level on axis=1 after unstacking on level=0:

s = df.unstack(level=0).droplevel(1, axis=1)
s['mplm'].plot(), s['unhappy'].plot()

enter image description here enter image description here

Related