89_Simple
89_Simple

Reputation: 3805

Multiple plotting device in R

To save multiple plots in a pdf, I do this:

  pdf("plot1.pdf")

  for(i in 1:10){
      p <- plot(rnorm(10))
      p
  }
  dev.off()

Is there any way I can open two pdf and print different plots in them. Something like

  pdf("plot1.pdf")
  pdf("plot2.pdf")

  for(i in 1:10){
     p1 <- plot(rnorm(10))
     p1 # print this in plot1.pdf

     p2 <- plot(rnorm(100))
     p2 # print this in plot2.pdf
  }
  dev.off()

Upvotes: 2

Views: 629

Answers (1)

MrFlick
MrFlick

Reputation: 206283

You can only have one graphics device active at a time, but you can switch between them. R tracks a list of open devices (dev.list()) in the order in which you create them. For example you can do

pdf("plot1.pdf")
pdf("plot2.pdf")

for(i in 1:3){
  dev.set(dev.prev()) #go back to plot1.pdf
  plot(rnorm(10))

  dev.set(dev.next()) # jump ahead to plot2.pdf
  plot(rnorm(100))
}
dev.off()
dev.off()

(Note it doesn't make sense to store the result of plot(rnorm(10)) to a variable because it doesn't return anything. Base plotting typically just have the side effect of drawing to the screen.)

Upvotes: 2

Related Questions