Show counts on a stacked bar plotΒΆ

[1]:
from plotnine import *
from plotnine.data import mtcars

%matplotlib inline

A stacked bar plot.

[2]:
(ggplot(mtcars, aes('factor(cyl)', fill='factor(am)'))
 + geom_bar( position='fill')
)
../_images/tutorials_miscellaneous-show-counts-on-a-stacked-bar-plot_3_0.png
[2]:
<ggplot: (97654321012345679)>

We want to know how many items are in each of the bars, so we add a geom_text with the same stat as geom_bar and map the label aesthetic to the computed count.

[3]:
(ggplot(mtcars, aes('factor(cyl)', fill='factor(am)'))
 + geom_bar(position='fill')
 + geom_text(aes(label='stat(count)'), stat='count')
)
../_images/tutorials_miscellaneous-show-counts-on-a-stacked-bar-plot_5_0.png
[3]:
<ggplot: (97654321012345679)>

Not what we wanted.

We forgot to give geom_text the same position as geom_bar. Let us fix that.

[4]:
(ggplot(mtcars, aes('factor(cyl)', fill='factor(am)'))
 + geom_bar( position='fill')
 + geom_text(aes(label='stat(count)'), stat='count', position='fill')
)
../_images/tutorials_miscellaneous-show-counts-on-a-stacked-bar-plot_7_0.png
[4]:
<ggplot: (97654321012345679)>

That is more like it