How to transform Pandas df for stacked bargraph
Question:
I have the following df resulting from:
plt_df = df.groupby(['Aufnahme_periode','Preisgruppe','Land']).count()
INDEX Aufnahme_periode Preisgruppe Land Anzahl
1344 2021-11-01 1 NL 2
1345 2021-12-01 1 AT 8
1346 2021-12-01 1 BE 1
1347 2021-12-01 1 CH 1
1348 2021-12-01 1 DE 154
1349 2021-12-01 1 GB 3
1350 2021-12-01 1 JP 1
1351 2021-12-01 1 NL 2
1352 2022-01-01 1 AT 1
1353 2022-01-01 1 DE 19
1354 2022-01-01 1 IT 1
1355 2022-01-01 2 CH 1
1356 2022-01-01 2 DE 1
1357 2022-02-01 1 DE 16
1358 2022-02-01 1 FR 1
1359 2022-02-01 2 CH 1
1360 2022-03-01 1 DE 23
I would like to make two bar charts:
1:
Monthly signup by "Preisgruppe" so stack group 2 on top of group 1:
The df should probably have columns for group 1 and 2 and rows for each month.
2:
Monthly signup by country:
Same as above, one column for each country and rows for the months.
I think I know how to make the charts, I just need help transforming the df.
Answers:
You need a pivot_table
:
(plt_df
.pivot_table(index='Aufnahme_periode', columns='Preisgruppe',
values='Anzahl', aggfunc='sum')
.plot.bar(stacked=True)
)
output:
Same thing for the countries, just use 'Land'
in place of 'Preisgruppe'
:
output:
I have the following df resulting from:
plt_df = df.groupby(['Aufnahme_periode','Preisgruppe','Land']).count()
INDEX Aufnahme_periode Preisgruppe Land Anzahl
1344 2021-11-01 1 NL 2
1345 2021-12-01 1 AT 8
1346 2021-12-01 1 BE 1
1347 2021-12-01 1 CH 1
1348 2021-12-01 1 DE 154
1349 2021-12-01 1 GB 3
1350 2021-12-01 1 JP 1
1351 2021-12-01 1 NL 2
1352 2022-01-01 1 AT 1
1353 2022-01-01 1 DE 19
1354 2022-01-01 1 IT 1
1355 2022-01-01 2 CH 1
1356 2022-01-01 2 DE 1
1357 2022-02-01 1 DE 16
1358 2022-02-01 1 FR 1
1359 2022-02-01 2 CH 1
1360 2022-03-01 1 DE 23
I would like to make two bar charts:
1:
Monthly signup by "Preisgruppe" so stack group 2 on top of group 1:
The df should probably have columns for group 1 and 2 and rows for each month.
2:
Monthly signup by country:
Same as above, one column for each country and rows for the months.
I think I know how to make the charts, I just need help transforming the df.
You need a pivot_table
:
(plt_df
.pivot_table(index='Aufnahme_periode', columns='Preisgruppe',
values='Anzahl', aggfunc='sum')
.plot.bar(stacked=True)
)
output:
Same thing for the countries, just use 'Land'
in place of 'Preisgruppe'
:
output: