MaM
MaM

Reputation: 2069

Pandas plot subplots of a 'group by' result

I struggle with my (poor) Pandas knowledge, as I try to get a bar plot on a hierachial index by a group by operation.

My data look like this

id, val, cat1, cat2

Then I create a hierachical index:

df_group = df_len.groupby(['cat1','cat2'])

I would like to get a hbar plot per cat1 object that lists all cat2 objects that lists the values of all cat1 objects within.

None of my approaches worked:

The result should look somewhat like this one enter image description here

I guess I just lack of knowledge of pandas, matplotlib, ... -internals and it's not that difficult to plot a few 100 items (cat2<10, cat1=30)

.

Upvotes: 1

Views: 2130

Answers (3)

MaM
MaM

Reputation: 2069

Ok guys, so here it's how I solved it finally:

dfc = df_len.groupby(['cat1','cat2']).count().reset_index()
dfp=dfc.pivot(index="cat1",columns="cat2")
dfp.columns = dfp.columns.get_level_values(1)
dfp.plot(kind='bar', figsize=(15, 5), stacked=True);

In short: I used a pivot table to transpose my matrix and then I was able to plot the single cols automaticly, at example 2 here.

Upvotes: 2

CT Zhu
CT Zhu

Reputation: 54400

Not so tricky in matplotlib, see:

In [54]:

print df
  cat1  cat2       val
0    A     1  0.011887
1    A     2  0.880121
2    A     3  0.034244
3    A     4  0.530230
4    B     1  0.510812
5    B     2  0.405322
6    B     3  0.406259
7    B     4  0.406405
In [55]:

col_list = ['r', 'g']
ax = plt.subplot(111)
for (idx, (grp, val)) in enumerate(df.groupby('cat1')):
    ax.bar(val.cat2+0.25*idx-0.25, 
           val.val, width=0.25,  
           color=col_list[idx], 
           label=grp)
plt.legend()

enter image description here

Upvotes: 1

b10n
b10n

Reputation: 1186

I'd recommend using seaborn to do this type of faceted plot. Doing it in matplotlib is very tricky as the library is quite low level. Seaborn excels at this use case.

Upvotes: 2

Related Questions