Home > database >  How can I add an annotation to a faceted ggplot (with a log scale) outside the plot area
How can I add an annotation to a faceted ggplot (with a log scale) outside the plot area

Time:05-12

I'm looking to add some annotations (ideally a text and an arrow) to a faceted ggplot outside the plot area.

What's that, you say? Hasn't someone asked something similar enter image description here

CodePudding user response:

I think I would use annotation_custom here. This requires standard coord_cartesian with clip = 'off', but it should be easy to re-jig your x axis to use scale_x_log10

plot_data %>%
  ggplot()  
  aes(
    x = estimate,
    y = term,
    colour = stat_sig)  
  geom_vline(
    aes(xintercept = 1),
    linetype = 2
  )  
  geom_point(
    shape = 15,
    size = 4
  )  
  geom_linerange(
    xmin = (log10(plot_data$conf.low)),
    xmax = (log10(plot_data$conf.high))
  )  
  scale_colour_manual(
    values = c(
      "N.S." = "black",
      "p < 0.05" = "red")
  )  
  annotation_custom(
    grid::textGrob( 
    x = unit(0.4, 'npc'),
    y = unit(-7.5, 'mm'),
    label = "indicates yada",
    gp = grid::gpar(col = 'red', vjust = 0.5, hjust = 0.5))
  )  
  annotation_custom(
    grid::textGrob( 
      x = unit(0.6, 'npc'),
      y = unit(-7.5, 'mm'),
      label = "indicates bada",
      gp = grid::gpar(col = 'blue', vjust = 0.5, hjust = 0.5))
  )  
  annotation_custom(
    grid::linesGrob( 
      x = unit(c(0.49, 0.25), 'npc'),
      y = unit(c(-10, -10), 'mm'),
      arrow = arrow(length = unit(3, 'mm')),
      gp = grid::gpar(col = 'red'))
  )  
  annotation_custom(
    grid::linesGrob( 
      x = unit(c(0.51, 0.75), 'npc'),
      y = unit(c(-10, -10), 'mm'),
      arrow = arrow(length = unit(3, 'mm')),
      gp = grid::gpar(col = 'blue'))
  )  
  labs(
    y = "",
    x = "Hazard ratio")  
  scale_x_log10(
    breaks = c(0.1, 0.3, 1, 3, 10),
    limits = c(0.1,10))  
  ggforce::facet_col(
    facets = ~group,
    scales = "free_y",
    space = "free"
  )  
  coord_cartesian(clip = 'off')  
  theme(
    legend.position = "bottom",
    legend.title = element_blank(),
    strip.text = element_text(hjust = 0),
    axis.title.x = element_text(margin = margin(t = 25, r = 0, b = 0, l = 0)),
    panel.spacing.y = (unit(15, 'mm'))
  )

enter image description here

  • Related