Ibidamola Olley
Ibidamola Olley

Reputation: 23

multiple plots on a page

I would like for it to have 4plots to a single page instead of just 1 plot per page and is there a way i can use ggarrange from the loop to have 4 different plots on a single page?

library(ggplot2)

n <- 10 # number of plots
x <- rnorm(50, mean = 20)
y <- 2*x + 1 + rnorm(50)
df <- data.frame(x = x, y = y)
  
pdf("test.pdf", onefile = TRUE)
for(i in seq(n)){
  df$x <- df$x + rnorm(50, sd = 0.01)
  df$y <- df$y + rnorm(50, sd = 0.01)
  p <- ggplot(data = df) + aes(x, y) + 
    geom_point()
  print(p)
}
dev.off() # close device

Upvotes: 2

Views: 301

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388982

You can try this -

# number of plots
n <- 10 
#Create a dataframe
x <- rnorm(50, mean = 20)
y <- 2*x + 1 + rnorm(50)
df <- data.frame(x = x, y = y)

pdf("test.pdf", onefile = TRUE)
#for n = 10, loop will run 3 times. 
#It will generate 4, 4, and 2 plots
for(i in seq(ceiling(n/4))) {
  #For the last page
  if(n > 4) k <- 4 else k <- n
  n <- n - 4
  #Create a list to store the plots
  plot_list <- vector('list', k)
  for(j in 1:k) {
    df$x <- df$x + rnorm(50, sd = 0.01)
    df$y <- df$y + rnorm(50, sd = 0.01)
    plot_list[[j]] <- ggplot(data = df) + aes(x, y) + geom_point() 
  }
  #Print multiple plots together
  print(do.call(gridExtra::grid.arrange, plot_list))
}
dev.off()

Upvotes: 2

Related Questions