rggplot2annotate

How can I add some text to a ggplot2 graph in R outside the plot area?


enter image description hereI have a simple dataset in R.

horz <- rnorm(100)
letters <- letters[1:10]
dat <- data.frame(horz, letters)

I am plotting a graph using ggplot2.

library(ggplot2)
ggplot(dat, aes(x = horz, y = letters)) +
        geom_point(alpha = 0.3) +
        stat_summary(fun = mean, geom = "point", size = 3, color = "red")

I want to add some text on the y-axis that spans 3 categories of the y-axis variable and runs over 3 lines. Just like in the figure attached. How can I achieve that? I appreciate your help.


Solution

  • As documented in ggplot2 - annotate outside of plot or Add text outside plot area you can use annotate or annotation_custom to add a label outside of the plot area. Personally I prefer annotation_custom as it allows to place the label using units as well as data coordinates. Additionally, for your use case I would use gridtext::textbox_grob which allows your to draw a box around the label spanning the desired number of categories.

    library(ggplot2)
    library(gridtext)
    
    set.seed(123)
    
    horz <- rnorm(100)
    letters <- letters[1:10]
    dat <- data.frame(horz, letters)
    
    ggplot(dat, aes(x = horz, y = letters)) +
      geom_point(alpha = 0.3) +
      stat_summary(fun = mean, geom = "point", size = 3, color = "red") +
      annotation_custom(
        textbox_grob(
          text = "Age 0-6m\nReference\ngroup",
          orientation = "left-rotated",
          x = unit(0, "npc") - unit(16, "pt"),
          vjust = 0,
          halign = .5,
          gp = grid::gpar(
            lineheight = 1,
            fontsize = 10
          ),
          box_gp = grid::gpar(
            col = "black"
          ),
          padding = unit(rep(5, 4), "pt")
        ),
        ymin = "b", ymax = "d"
      ) +
      # Set clip="off"
      coord_cartesian(clip = "off") +
      # Add space for the label
      theme(plot.margin = margin_part(l = 40))
    

    enter image description here