Can someone please help me how I can add the value labels to a stacked barplot in ggplot? Is there a way I can calculate the percentages using geom_bar()
or do I have to calculate the percentages manually and then use geom_col()
?
library(tidyverse)
df <- data.frame(var1 = sample(c("A","B"), size = 100, replace=TRUE),
var2 = sample(c("x", "y"), size=100, replace=TRUE))
df %>%
ggplot(aes(x = var1, fill = var2)) +
geom_bar(position = 'fill') +
geom_text(aes(x = var1, fill = var2, label = "x")) <= ???
Thanks for help!
While stat_count
computes some percentages under the hood (which can be accessed via ..prop..
or after_stat(prop)
most of the time you have to compute the percentages manually. Therefore the easier way would probably be to summarizing your data before passing it to ggplot2. However, my answer below shows you one approach to compute the percentages on the fly using after_stat
and tapply
:
library(tidyverse)
df <- data.frame(var1 = sample(c("A","B"), size = 100, replace=TRUE),
var2 = sample(c("x", "y"), size=100, replace=TRUE))
df %>%
ggplot(aes(x = var1, fill = var2)) +
geom_bar(position = 'fill') +
geom_text(aes(x = var1,
label = scales::percent(after_stat(count / tapply(count, x, sum)[x])),
group = var2), position = "fill", stat = "count")