rggplot2stacked-chart

Label column in stacked bar chart ggplot2


I am creating a stacked bar chart using the following code:

df <- structure(list(stage = structure(c(2L, 3L, 2L, 
2L, 2L, 3L, 1L, 3L, 1L, 3L, 2L, 2L, 1L, 2L, 2L, 3L, 2L, 3L, 2L, 
2L, 3L, 2L, 3L, 2L, 2L, 2L, 3L, 2L, 2L, 2L, 3L), levels = c("1", 
"2", "3"), class = c("ordered", "factor")), group = structure(c(2L, 
1L, 1L, 1L, 2L, 1L, 1L, 3L, 2L, 2L, 2L, 1L, 1L, 1L, 2L, 3L, 2L, 
1L, 1L, 1L, 1L, 3L, 2L, 2L, 1L, 3L, 2L, 3L, 1L, 3L, 3L), levels = c("1", 
"2", "3"), class = c("ordered", "factor"))), row.names = 10:40, class = "data.frame")

bp <- ggplot(data=df , aes(fill = stage, x=forcats::fct_rev(group))) + 
  geom_bar(position = "fill", width = 0.7, color = "black", size = 0.2) + 
  coord_flip()

enter image description here

I would like to label the top column with the different levels for "stage" ie. "stage 3", "stage 2", "stage 1", something similar to this:

enter image description here

Any suggestions how to accomplish this?


Solution

  • The simplest way to do this is probably with a secondary y axis

    ggplot(data=df , aes(fill = stage, x=forcats::fct_rev(group))) + 
      geom_bar(position = "fill", width = 0.7, color = "black", size = 0.2) + 
      coord_flip() +
      scale_y_continuous(sec.axis = sec_axis(~.x, breaks = c(0.13, 0.55, 0.92),
                                             labels = c("Oil", "Coal", "Gas"))) +
      scale_x_discrete(expand = c(0.05, 0.05)) +
      theme_minimal(base_size = 20) +
      theme(axis.ticks = element_line())
    

    enter image description here