Search code examples
rggplot2graphtidyverse

Add vertical text in the top margin of ggplot


I have the following code for a plot

ggplot(na.omit(total), aes(x = day_after, y = use, group=t, na.rm=TRUE)) +
  geom_line(aes(linetype=t, color=t, na.rm=TRUE))+
  geom_point(aes(color=t, na.rm = TRUE)) +
  scale_color_manual(values=c("gray48", "indianred4"), labels=c("Treatment","Control")) +
  labs(x= "Days after beginning of deactivation period", y= "") +
  theme(panel.grid.minor = element_blank(),
        panel.background = element_blank()) +
  theme(panel.grid.major.x = element_blank(),
    panel.grid.major.y = element_line( size=.1, color="grey"))+
  theme(legend.key=element_blank()) +
  guides(linetype = FALSE) +
  annotate('segment',x = 0,xend = 0,y = 0,yend = 60,size = 3,colour = "grey",
           alpha = 0.4) +
  annotate('segment',x = 7,xend = 7,y = 0,yend = 60,size = 3,colour = "grey",
                                 alpha = 0.4) +
  annotate('segment',x = 39,xend = 39,y = 0,yend = 60,size = 3,colour = "grey",
           alpha = 0.4) 
new_plot <- plot + theme(legend.title=element_blank(), legend.text = element_text(size=10),
      legend.position = "right")

enter image description here

What I want to do is to add vertical text on the top the plot at multiple given (x,y) values, outside the plot. Annotate_custom works but it does not have the option to rotate the text. Basically I tried + annotation_custom(text_end,xmin=42,xmax=42,ymin=62,ymax=62) Which would be amazing, only i cannot have an option like angle=90. Any help ??


Solution

  • You can use annotation_custom, as long as you turn clipping off. You can use a custom grid::textGrob to specify rotation.

    I don't have your data, but an example using the built-in mtcars dataset should suffice for illustration.

    library(ggplot2)
    
    ggplot(mtcars, aes(disp, mpg)) + 
      geom_point() +
      geom_vline(xintercept = c(200, 400), size = 10, alpha = 0.05) +
      coord_cartesian(clip = "off") +
      theme_bw() +
      theme(plot.margin = margin(80, 20, 20, 20),
            panel.border = element_blank()) +
      annotation_custom(grid::textGrob("label 1", rot = 90), 
                        xmin = 200, xmax = 200, ymin = 40) +
      annotation_custom(grid::textGrob("label 2", rot = 90), 
                        xmin = 400, xmax = 400, ymin = 40)
    

    enter image description here