Search code examples
ggplot2axisannotateyaxis

Add boxes with descriptive annotations to y-axis in ggplot2


I"M trying to add another label or description to my Y axis. I attached a picture for reference for what I'm trying to accomplish. I can't find anything that describes how to add additional elements to an axis. It the "Good" and "Bad" boxes beside the Y axis that I"m trying to incorporate into my ggplot. Thanks!

enter image description here


Solution

  • One approach to achieve this is by using patchwork. You can set up the annotations of the y-axis as a second ggplot and glue it to your main plot using patchwork. Try this:

    library(ggplot2)
    library(patchwork)
    library(dplyr)
    
    p1 <- tibble(x = 1:10, y = 1:10) %>% 
      ggplot(aes(x, y)) +
      geom_point() +
      scale_y_reverse(breaks = seq(1, 10)) +
      labs(y = NULL)
    
    p2 <- tibble(ymin = c(0, 4), ymax = c(4, 10), fill = c("bad", "good")) %>% 
      ggplot() +
      geom_rect(aes(xmin = 0, xmax = 1, ymin = ymin, ymax = ymax, fill = fill)) +
      geom_text(aes(x = .5, y = (ymin  + ymax) / 2, label = fill), angle = 90) +
      scale_y_reverse(breaks = seq(1, 10), expand = expansion(mult = c(0, 0))) +
      scale_x_continuous(breaks = c(0), expand = expansion(mult = c(0, 0))) +
      guides(fill = FALSE) +
      theme_void()
    
    p2 + p1 + plot_layout(widths = c(1, 9))
    

    Created on 2020-05-28 by the reprex package (v0.3.0)