William Baker Morrison
William Baker Morrison

Reputation: 1789

Plotting a stacked dataframe

I would like to use the pandas.DataFrame.plot.bar(stacked=True) functionality to visualise my dataframe (see below head).

Selecting 1 period, I would like the "num" for each "Wave" to be stacked across "Electrodes". Ideally, each period would be plotted in a separate subplot. Current code:

one = df[df["Period"]=="1"]
one.plot.bar(stacked=True);
plt.show()

current datafram

In the example below, this would mean a,b,c,d represent the different Waves and 0-9 represent the different electrodes.

stacked plot example

I think it's a matter of re-ordering my dataframe to the expectations of plot.bar, but I'm not sure how to proceed.

Here's the first 30 rows of the DataFrame

    Electrode   Period  Wave    num
0   7   10  Beta    1
1   8   12  Beta    1
2   15  10  High gamma  1
3   4   10  Theta   1
4   11  4   High gamma  1
5   12  13  High gamma  3
6   11  4   Delta   3
7   11  4   Theta   0
8   14  0   Delta   2
9   14  1   Beta    0
10  11  6   Low gamma   1
11  1   9   Theta   0
12  8   1   Theta   0
13  5   8   Theta   0
14  10  0   Low gamma   2
15  13  12  Alpha   1
16  8   13  Alpha   1
17  10  0   Beta    1
18  7   5   Alpha   2
19  10  3   Theta   0
20  14  6   High gamma  2
21  4   11  Beta    1
22  4   5   Delta   1
23  4   10  High gamma  2
24  10  0   High gamma  3
25  12  4   Alpha   1
26  8   8   Theta   0
27  8   11  Beta    1
28  6   2   Delta   2
29  12  7   Low gamma   3

Upvotes: 1

Views: 96

Answers (2)

jezrael
jezrael

Reputation: 863801

I think need groupby and aggregate mean with unstack for reshape:

one = df[df["Period"]==10].groupby(['Electrode','Wave'])['num'].mean().unstack()
one.plot.bar(stacked=True)

For all subplots:

grouped = df.groupby('Period')
nrows = int(math.ceil(len(grouped)/2.))
fig, axs = plt.subplots(nrows,2, figsize=(12,30))

for (name, df), ax in zip(grouped, axs.flat):
    df.groupby(['Electrode','Wave'])['num'].mean().unstack().plot.bar(stacked=True, ax=ax)

Upvotes: 1

William Baker Morrison
William Baker Morrison

Reputation: 1789

Following the error inspired by jezrael, I found this solution :

df[df["Period"]=="1"].pivot_table(values="num", index=["Electrode"], columns="Wave", aggfunc='mean').plot.bar(stacked=True)

Upvotes: 0

Related Questions