Show counts on a stacked bar plotΒΆ

[1]:
from plotnine import (
    ggplot,
    aes,
    after_stat,
    geom_bar,
    geom_text
)
from plotnine.data import mtcars

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]:
<Figure Size: (640 x 480)>

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=after_stat('count')), stat='count')
)
../_images/tutorials_miscellaneous-show-counts-on-a-stacked-bar-plot_5_0.png
[3]:
<Figure Size: (640 x 480)>

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=after_stat('count')), stat='count', position='fill')
)
../_images/tutorials_miscellaneous-show-counts-on-a-stacked-bar-plot_7_0.png
[4]:
<Figure Size: (640 x 480)>

That is more like it