Histogram in Pandas groupby with matplotlib
I have a datafrme on which I am doing groupby on two columns:
ax = df_all.groupby(['Component', 'SubComponent' ])['SubComponent'].count()
And that gives me the following:
--------------------------------------------------
| Component | SubComponent| |
--------------------------------------------------
|A |First | 1|
--------------------------------------------------
| |Second | 10|
--------------------------------------------------
| |Third | 6|
--------------------------------------------------
|B |First | 8|
--------------------------------------------------
| |Second | 5|
--------------------------------------------------
| |Third | 17|
--------------------------------------------------
Now I would like to make a histogram out of it. Each bar will be a Component and each component will be divided into SubComponents showing the number of times each SubComponent will appear with a different color.
Is there an easy way to accomplish this using matplotlib.pyploy?
Thanks, Submi
+3
source to share
1 answer
You can use unstack
with DataFrame.plot.bar
:
print (ax.unstack())
SubComponent First Second Third
Component
A 1 4 15
B 6 2 1
ax.unstack().plot.bar(stacked=True)
print (ax.unstack(0))
Component A B
SubComponent
First 1 6
Second 4 2
Third 15 1
ax.unstack(0).plot.bar(stacked=True)
Note:
+2
source to share