rdataframeggplot2geom-bar

Adding a bar with total count per group for geom_bar


I'm trying to make a bar plot with two grouping variables that will also include a bar with total count from one group. The code below gets me a bar plot with the two grouping variables the way I want them, but I would also like to add another bar for 2016 and 2017 with the sum of the grp variable (12 for 2016, 15 for 2017).

x<-data.frame(grp=rep(c("x1",  "x2", "x3"), 9), yr=c(rep(2016,4), rep(2017,5)))

ggplot(x)+
  geom_bar(aes(x=yr, fill=grp), position="dodge")

Solution

  • I don't like hard-coding the totals;

    library(dplyr)
    library(ggplot2)
    
    x %>% 
      mutate(yr = factor(yr)) %>% 
      summarise(count = n(), .by = c(grp, yr)) %>% 
      bind_rows(., reframe(., grp = "Total", count = sum(count), .by =yr)) %>% 
     ggplot()+
      geom_bar(aes(x=yr, y=count, fill=grp), position="dodge", stat = "identity")
    

    Created on 2024-04-09 with reprex v2.0.2