Search code examples
rggplot2geom-bargeom-text

How to swap labels on stacked bar graph using geom_text?


When producing a stacked bar graph that has different color by facet variable and bar fill variable, I would like to add the number/count by each color. I am using the geom_text function by it seems to be swapping the order of the numbers for each bar.

The code I am using is below:

ggplot(data241, aes(x=Disease, y = n, fill = DisCat1)) + 
  geom_bar(aes(alpha = Case.Status), stat = "identity") +   
  facet_grid(DisCat1~., scales = "free", space = "free") +
  scale_alpha_manual(values = c(0.2, 1)) + scale_fill_manual(values= scale_color) + 
  geom_text(aes(label=n)) 

and I am producing this graph: enter image description here

I have circled one example on each facet to show the problem.


Solution

  • As you have a stacked bar chart you need to set position="stack" for geom_text too. Additionally you have to ensure the same grouping, i.e. for geom_bar the grouping is the interaction of disCat1 and Case.Status aka the variables mapped on fill and alpha:

    Using a minimal reproducible example base on ggplot2::mpg to mimic your real data:

    library(ggplot2)
    library(dplyr, warn = FALSE)
    
    data241 <- mpg |>
      filter(
        drv %in% c("r", "f"),
        trans %in% c("manual(m5)", "auto(l4)", "auto(l5)")
      ) |>
      rename(Disease = class, Case.Status = drv, DisCat1 = trans) |>
      count(Disease, Case.Status, DisCat1)
    
    ggplot(data241, aes(x = Disease, y = n, fill = DisCat1)) +
      geom_bar(aes(alpha = Case.Status), stat = "identity") +
      facet_grid(DisCat1 ~ ., scales = "free", space = "free") +
      scale_alpha_manual(values = c(0.2, 1)) +
      geom_text(aes(
        label = n,
        group = interaction(DisCat1, Case.Status)
      ), position = position_stack(vjust = .5))