How to create stacked subplots with pandas
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Book End
--
Chapters
00:00 Question
00:46 Accepted answer (Score 4)
01:31 Answer 2 (Score 2)
01:48 Thank you
--
Full question
https://stackoverflow.com/questions/3270...
Question links:
[image]: https://i.stack.imgur.com/tqIOq.jpg
Accepted answer links:
[image]: https://i.stack.imgur.com/AXMA3.png
Answer 2 links:
[image]: https://i.stack.imgur.com/FTo8S.png
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #pandas #matplotlib
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Book End
--
Chapters
00:00 Question
00:46 Accepted answer (Score 4)
01:31 Answer 2 (Score 2)
01:48 Thank you
--
Full question
https://stackoverflow.com/questions/3270...
Question links:
[image]: https://i.stack.imgur.com/tqIOq.jpg
Accepted answer links:
[image]: https://i.stack.imgur.com/AXMA3.png
Answer 2 links:
[image]: https://i.stack.imgur.com/FTo8S.png
--
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))

