rggplot2textmarginannotate

ggplot2 text in top margin, flipped coordinates


I would like to add some text to a plot in the top margin, but all the solutions I could find messed up the flipped coordinate system after using coord_flip()

var1<- c("ab", "cd")
HR1<-c (0.51, 0.65)
lower1 <- c(0.4, 0.5)
upper1 <- c(0.6, 0.9)
forest1 <- data.frame(var1, HR1, lower1, upper1)
ggplot(data=forest1, aes(x=var1, y=HR1, ymin=lower1, ymax=upper1)) +
  geom_pointrange() +
  geom_hline(yintercept=1, lty=2) + 
  geom_hline(yintercept=0.4, lty=2) +  
  coord_flip() +  
  xlab("Label") + ylab("Mean (95% CI)") +
  theme_bw() +
  labs(x="", y="HR") + ylim(0.3, 1.1) +
  theme(plot.margin = unit(c(4, 1, 1, 1), "lines")) 

It should be like in the image. Is there a (simple) solution? Thanks!


Solution

  • An easy option to achieve your desired result would be to add your annotations using the secondary axis trick, i.e. add a secondary x axis and add your annotations via the axis text. And if you need some additional styling you could do so using e.g. ggtext.

    Note: I dropped the coord_flip and instead switched x and y.

    library(ggplot2)
    library(ggtext)
    
    ggplot(data = forest1, aes(y = var1, x = HR1, xmin = lower1, xmax = upper1)) +
      geom_pointrange() +
      geom_vline(xintercept = c(.4, 1), lty = 2) +
      scale_x_continuous(
        sec.axis = dup_axis(
          breaks = c(.325, .6, 1.075),
          labels = c("Words", "Words", "**More Words**")
        ),
        limits = c(0.3, 1.1)
      ) +
      theme_bw() +
      labs(x = NULL, y = "HR") +
      theme(
        axis.text.x.top = ggtext::element_markdown(size = 12),
        axis.ticks.x.top = element_blank()
      )