from plotnine import ggplot, aes, after_stat, geom_bar, geom_text
from plotnine.data import mtcars
Show counts on a stacked bar plot
A stacked bar plot.
"factor(cyl)", fill="factor(am)")) + geom_bar(position="fill")) (ggplot(mtcars, aes(
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
.
("factor(cyl)", fill="factor(am)"))
ggplot(mtcars, aes(+ 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.
("factor(cyl)", fill="factor(am)"))
ggplot(mtcars, aes(+ geom_bar(position="fill")
+ geom_text(aes(label=after_stat("count")), stat="count", position="fill")
)
That is more like it