looping and plotting multiple graphs on one page ggplot2/cowplot

I have a loop that plots two graphs per column from a large dataset. In that loop I now plot both graphs P1 and P2 on one page and then move on to the next page where the next column P1 P2 will be plotted.

However, before I go to the next page I actually want to plot multiple columns (P1 and P2) on one page: e.g. column 1 P1 and P2, column 2 P1 and P2 and then move to the next page.

please find below a simplification of the code that I use now.

Making the dataset

library(ggplot2)
library(cowplot)

    group <- c("Control","PAD","Control","PAD","PAD", "Control","PAD","Control","PAD","PAD", "Control","PAD","Control","PAD","PAD")
b <- round(runif(15, 1, 7)) 
c <- round(runif(15, 1, 3)) 
d <- round(runif(15, 3, 8)) 
e <- round(runif(15, 1, 5))
tissue <- c("Homogenate", "Plasma" , "Homogenate" , "Plasma" , "Homogenate", "Plasma" , "Homogenate" , "Plasma", "Homogenate", "Plasma" , "Homogenate" , "Plasma", "Homogenate", "Plasma" , "Homogenate")


df <- data.frame(group, b,c,d, e, tissue)
df

rm(group, b, c, d, e, tissue)

running through the dataset while making two graphs per column and store those in PDF

  pdf("------------.pdf", width = 15)
for (i in names(df)[2:5]){

p1 <- ggplot(df, aes_string("tissue",i)) + 
  geom_boxplot(show.legend = F)



p2 <- ggplot(df, aes_string("tissue",i)) + 
  geom_boxplot(show.legend = F)


p_all <- plot_grid(p1,p2)



# create a title vector for i
title <- ggdraw() +
  draw_label(i, 
             fontface = "bold",
             x = 0,
             hjust = 0,
             size = 25) +
  theme(
    # add margin on the left of the drawing canvas
    plot.margin = margin(0,0,0,7,))




p_all <- plot_grid(title, p_all, ncol=1, nrow=3, rel_heights = c(0.1,1))
print(p_all)
} 
dev.off()

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.