Home > Net >  Empty plot space in patchwork same size as all other plots
Empty plot space in patchwork same size as all other plots

Time:03-07

I am plotting a series of identically sized plots in a grid using patchwork. My grid is 5 x 6, expect for the final 2 rows I have only 4 plots in the row not 5. I want to have empty plots so that the plots are displayed as a regular grid.

XXXXX
XXXXX
XXXXX
XXXXX
XXXX
XXXX

With cowplot I could use NULL, but found the spacing was odd so switched to patchwork. plot_spacer() is not working as I expected as it changes the alignment of the rest of the row.

Example grid - bottom row containing plot_spacer() is not well aligned

library(tidyverse)
library(latex2exp)
library(patchwork)


genCircle <-
  function(center = c(0.0, 0.0), 
           rad = 1.0,
           npoints = 100) {
    # fcn for circle plots
    r = rad
    tt <- seq(0, 2 * pi, length.out = npoints)
    xx <- center[1]   r * cos(tt)
    yy <- center[2]   r * sin(tt)
    return(data.frame(x = xx, y = yy))
  }

dat = genCircle()

line1 = sprintf("$A = %0.2f$, $B = %0.3f$",
                1.6,
                3.7
)

line2 = sprintf("$\\hat{C} = %0.1f$,$ \\hat{%s} = %0.1f$",
                12.6,
                "D",
                86.3
)


p1 <- ggplot(data = dat, mapping = aes(x = x, y = y))   
  geom_path(size =0.3)    
  geom_abline(color = 'gray77', size = 0.1)   
  coord_fixed()  
  ggtitle(TeX(line1))    labs(subtitle = TeX(line2))  
  theme(plot.title = element_text(size = 9, hjust = 0, margin=margin(b=0)), plot.subtitle = element_text(size = 9, hjust = 0, margin=margin(b=0)), legend.title = element_blank(), legend.margin=margin(l = -2, unit='pt'), axis.text.x=element_blank(), axis.ticks.x=element_blank(), axis.text.y=element_blank(), axis.ticks.y=element_blank(), axis.title = element_blank(), plot.margin = unit(c(0.1,-0.1,0,0), "cm"))

(p1|p1|p1) / (p1|p1|p1) / (p1|p1|plot_spacer())

Is there a simple way to keep the grid structure?

CodePudding user response:

For a regular grid with empty plots at specific positions, patchwork::plot_layout takes a design argument where empty fields can be place with #

p7 <- p6 <- p5 <- p4 <- p3 <- p2 <- p1

design <- "
  123
  45#
  67#
"

p1   p2   p3   p4   p5   p6   p7   plot_layout(design = design)

enter image description here

  • Related