How to create stacked subplots with pandas
--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Island
--
Chapters
00:00 How To Create Stacked Subplots With Pandas
00:31 Accepted Answer Score 4
00:53 Answer 2 Score 2
01:04 Thank you
--
Full question
https://stackoverflow.com/questions/3270...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #pandas #matplotlib
#avk47
    Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Island
--
Chapters
00:00 How To Create Stacked Subplots With Pandas
00:31 Accepted Answer Score 4
00:53 Answer 2 Score 2
01:04 Thank you
--
Full question
https://stackoverflow.com/questions/3270...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #pandas #matplotlib
#avk47
ACCEPTED ANSWER
Score 4
I think - but I'm not sure - that it is difficult to combine stacked and subplots options. So here is a solution producing - I hope - the expected output but may be improved.
# Test data
np.random.seed(1234)
test = pd.DataFrame({'week':[1,1,1,1,1,1,2,2,2,2,2,2],
                     'score':np.random.uniform(0,1,12),
                    'type': [0,1,0,1,0,1,0,1,0,1,0,1],
                     'type2':[3,3,4,4,5,5,3,3,4,4,5,5]})
grouped = test.groupby(['type','week','type2']).agg('sum')
# Preparing plots
fig, axes = plt.subplots(nrows=2)
for group_name, group in grouped.groupby(level=0):
    group.index = group.index.droplevel(0)
    group = group.unstack(1)
    group.columns = group.columns.droplevel()
    group.plot(kind='bar', stacked=True, ax=axes[group_name], title='type: ' + str(group_name))

