1

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:

  • df_group.plot(...)
  • for name, group in df_group: .... group.plot(...)
  • df_group.xs(...) experiments

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)

.

0

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I tried seaborn, but without any luck in my case. But it seems to be a nice piece of code for higher dim data :)
2

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.

Comments

1

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

1 Comment

Nice idea, but I solved it finally with pure pandas and avoided the matplot tricks. But anyway, thanks for your help!

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.