Search code examples
rggplot2geom-bargeom-text

ggplot2 - How do I add proportion labels to stacked proportion barplot?


I have a grouped stacked proportion barplot that I created like this:

df <- data.frame(version = c("Version #1", "Version #2", "Version #1", "Version #2", "Version #1", "Version #2"),
                 result = c("good", "good", "ok", "ok", "bad", "bad"), 
                 amount = c(1608, 616, 2516, 979, 938, 266)) 

ggplot(df, aes(x=version,y=amount, fill=result, group = result)) + 
geom_bar(stat = "identity", position="fill") 

enter image description here

My questions is, how can I add proportion labels to the plot. Something like this:

enter image description here


Solution

  • With pipes and usuals:

    library(tidyverse)
    
    df %>%
      group_by(version) %>%
      mutate(label = gsub('^[0](\\.\\d{1,2}).*', '\\1', amount / sum(amount))) %>%
      ungroup() %>%
      ggplot(aes(x = version, y = amount, fill = result, label = label, vjust = 2)) + 
      geom_col(position = "fill", alpha = .5) +
      geom_text(position = 'fill') +
      scale_fill_brewer(palette = 'Set1') +
      ggthemes::theme_tufte() +
      theme(axis.title.x = element_blank(), axis.ticks = element_blank(),
            legend.title = element_blank())
    

    enter image description here