
Trying to add labels of count to my stacked bar chart
Hi everyone,
thank you everyone who has taken the time to help me before, I am really, really appreciative. Since I don't know the language that well yet and I am very much learning by doing, as I finish the project I am working on presently, I struggle with finding the errors, when I apply the answers others were given online.
I have created a stacked bar chart and I would very much like to add counts to the columns.
surveyresponses_Freizeit_Master_for_stacked %>%
pivot_longer(-Arbeit, names_to = "Group", values_to = "value") %>%
summarise(count = sum(value), .by = c("Arbeit", "Group")) %>%
ggplot(aes(Group, count, fill = Arbeit,)) +
geom_col() +
theme(axis.text.x = element_text(angle = 60, vjust = 1, hjust=1))
This would be my code, and it produced the graph as I need it... However, when I tried to add the count, based on this code that tackled a similar problem:
# Source - https://stackoverflow.com/a/63656093
# Posted by stefan, modified by community. See post 'Timeline' for change history
# Retrieved 2026-05-13, License - CC BY-SA 4.0
library(ggplot2)
ggplot(mtcars, aes(cyl, fill = factor(gear))) +
geom_bar(position = "fill") +
geom_text(aes(label = after_stat(count)),
stat = "count", position = "fill"
)
I receive this result:
Browse[1]> surveyresponses_Freizeit_Master_for_stacked %>%
+ pivot_longer(-Arbeit, names_to = "Group", values_to = "value") %>%
+ summarise(count = sum(value), .by = c("Arbeit", "Group")) %>%
+ ggplot(aes(Group, fill = Arbeit, label = after_stat(count)), stat = "count") +
+ geom_col() +
+ theme(axis.text.x = element_text(angle = 60, vjust = 1, hjust=1))
Error during wrapup: Problem while mapping stat to aesthetics.
ℹ Error occurred in the 1st layer.
Caused by error:
! Aesthetics must be valid computed stats.
✖ The following aesthetics are invalid:
• `label = after_stat(count)`
ℹ Did you map your stat in the wrong layer?
I understand the error message, but I am not sure what I ned to change to get the desired result... Again, I appreciate any help!