rggplot2patchwork

Add annotation or title outsides border


In this example, I added a border to the three plots:

library(ggplot2)
library(patchwork)
theme_border <- theme_gray() + 
  theme(plot.background = element_rect(fill = NA, colour = 'black',
                                       size = 1, linetype = "dashed"))

ggplot() + 
ggplot() + 
ggplot() + 
    plot_layout(ncol=1, guides = "collect") + 
    plot_annotation(title = "Pred Sp", theme = theme_border)

Created on 2024-04-18 with reprex v2.0.2

The plot title is inside. Is it possible to place it outsides the border? Additionally, is it possible to draw a border with rounded corners?


Solution

  • Here is one hacky option which uses annotation_custom to fake a panel border with rounded corners using grid::roundrectGrob for an otherwise blank ggplot, then uses patchwork::inset_element to add the patch of your three plots:

    library(ggplot2)
    library(patchwork)
    
    ggplot() +
      annotation_custom(
        grid::roundrectGrob(
          r = unit(0.025, "snpc"),
          gp = grid::gpar(
            lty = "dashed", lwd = 1, fill = NA
          )
        )
      ) +
      coord_cartesian(clip = "off") +
      theme_void() +
      theme(plot.title = element_text(margin = margin(b = 5.5))) +
      labs(title = "Pred Sp") +
      inset_element(
        ggplot() +
          ggplot() +
          ggplot() +
          plot_layout(ncol = 1, guides = "collect"),
        left = 0, right = 1,
        top = 1, bottom = 0,
        on_top = FALSE
      )