I have the following data.frame and stacked barplot. Now, I'd like to add the percentage values to the bar segments using geom_text()
n <- 10000
test <- data.frame(value = sample(1:3, size = n, replace = TRUE),
grp = sample(c("A", "B", "C"), size = n, replace = TRUE),
item = sample(c("Item1", "Item2", "Item3", "Item4", "Item5", "Item6"), size = n, replace = TRUE)) %>%
mutate(value = as.factor(value))
test %>%
ggplot(aes(x = grp, fill = value, group = value)) +
geom_bar(position = 'fill') +
geom_text(aes(label = value), position = position_stack(vjust = 0.5), size = 2) +
facet_wrap(item ~., ncol = 2) +
coord_flip() +
scale_fill_manual(values = c("green", "yellow", "red"))
My problem with geom_text()
is, that I dont have a y-variable defined in ggplot()
, so that I get the following error message:
geom_text() requires the following missing aesthetics: y
Do I have to use geom_col()
instead and calculate the percentages myself or is it also possible with geom_bar()
?