Show counts on a stacked bar plot

from plotnine import ggplot, aes, after_stat, geom_bar, geom_text
from plotnine.data import mtcars

A stacked bar plot.

(ggplot(mtcars, aes("factor(cyl)", fill="factor(am)")) + geom_bar(position="fill"))

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.

(
    ggplot(mtcars, aes("factor(cyl)", fill="factor(am)"))
    + geom_bar(position="fill")
    + geom_text(aes(label=after_stat("count")), stat="count")
)

Not what we wanted.

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

(
    ggplot(mtcars, aes("factor(cyl)", fill="factor(am)"))
    + geom_bar(position="fill")
    + geom_text(aes(label=after_stat("count")), stat="count", position="fill")
)

That is more like it