Search code examples
rggplot2cowplot

Adjusted labels hidden for nested plots


How do I make adjusted labels in nested plot_grid plots not hide below other plots?

This works fine:

# label 'b' is visible on top of figure a
plot_grid(ggdraw(), ggdraw(), nrow=2, labels=c("a", "b"), hjust=c(-0.5, -5), vjust=c(1,-2))

enter image description here

But not this:

# label 'b' is invisible below figure a.
plot_grid(ggdraw(), 
      plot_grid(ggdraw(), ggdraw(),
         nrow=2, rel_heights = c(0.4, 0.6), labels=c("b", "c"), hjust=c(-5,-0.5), vjust=c(0.5,0)), 
      nrow=2, rel_heights = c(0.33, 0.66))

enter image description here


Solution

  • This is a clipping issue. plot_grid() uses ggplot to draw the grid, and ggplot clips contents that falls outside the plot panel. Your cut-off letter falls partially outside the plot panel:

    p1 <- ggdraw() + theme(plot.background = element_rect(fill = "#FF000080", color = NA))
    p2 <- ggdraw() + theme(plot.background = element_rect(fill = "#00FF0080", color = NA))
    p3 <- ggdraw() + theme(plot.background = element_rect(fill = "#0000FF80", color = NA))
    
    row <- plot_grid(p1, p2, nrow=2, rel_heights = c(0.4, 0.6),
              labels=c("b", "c"), hjust=c(-5,-0.5), vjust=c(0.5,0))
    plot_grid(p3, row, nrow=2, rel_heights = c(0.33, 0.66))
    

    enter image description here

    One solution is to disable this clipping:

    row_grob <- ggplotGrob(row)
    index <- grep("panel", row_grob$layout$name)
    row_grob$layout$clip[index] = "off"
    
    plot_grid(p3, row_grob,
              nrow=2, rel_heights = c(0.33, 0.66))
    

    enter image description here

    Alternatively, you could draw the labels after you have assembled the whole plot grid, using draw_label().