0

I have a loop running for 50 patients. In it, I produce plot_i and table_i. I need plot_1 and table_1 on page 1 of a pdf, plot_2 and table_2 on page 2, etc. The plot is produced using base r, not ggplot2, so grid.arrange does not work. When I try to use par and layout, it only picks up on the plots, not tables. How do I specify to layout/par that I need the plot AND the table, or is there another function that would work?

I tried using layout/par but it just picks out two plots for each page, and ignores the tables. I want something that does what grid.arrange(plot_i, table_i) would do.

jpsmith
  • 11,023
  • 5
  • 15
  • 36
hks
  • 1
  • 1
  • 1
    How are your tables produced? Are you using the `pdf()` function or an Rmarkdown document or something else? If you could share some sample data and code for, say, 2 simple example plots and 2 tables that would give us something to work with as well as help us understand what you're actually doing. – Gregor Thomas Apr 18 '23 at 18:46
  • The tables are produced using tableGrob and I'm using the pdf() function. – hks Apr 18 '23 at 20:13

1 Answers1

1

You can do this using some manipulations to the layout, and extending the use of some of the techniques found in this answer using grid, gridExtra, and gridBase:

Example Data

set.seed(123)
df <- data.frame(patient = rep(1:5, each = 10),
                 var1 = runif(50),
                 var2 = rnbinom(50, mu = 1, size = 0.25))

Code

pdf("example.pdf")
for(i in unique(df$patient)){
  dta <- df[df$patient == i, ]
  tab <- table(dta$var1, dta$var2)
  
  layout(matrix(1:2, nrow = 1))
  plot(dta$var1, dta$var2, main = paste0("Patient ", i))
  frame()
  vps <- gridBase::baseViewports()
  grid::pushViewport(vps$inner, vps$figure, vps$plot)
  grid::grid.draw(gridExtra::tableGrob(tab))
}
dev.off()

This will put a figure and table side by side on the plot and each individual patient will have be on their own page. You can play around with the layout/margins/positioning as needed for your real data. Good luck! enter image description here

jpsmith
  • 11,023
  • 5
  • 15
  • 36
  • Thanks but I can't seem to get it to work. I get the error: Error in dim(data) <- dim : dims [product 20] do not match the length of object [12]. Any idea why? – hks Apr 18 '23 at 20:53
  • Unfortunately I wont be able to provide much additional help without a a reproducible example – jpsmith Apr 18 '23 at 20:55