3

How can I plot 7 different graphs on one pdf page on R?

I currently use matplot, which doesn't seem to have this option. I need to plot columns of data against columns of data.

I initially tried to do this with the lattice library, but I can't seem to figure out how to plot the columns of data. It seems to want a function.

Rich Scriven
  • 97,041
  • 11
  • 181
  • 245
Islands
  • 255
  • 4
  • 10

2 Answers2

5

To create a pdf of plots, you can do something like this. To initialize a pdf document use the pdf function with a file name first. dev.off() at the end will close the graphics device and complete the pdf. Afterwards, you should see a new document in the working directory (in this example - 'plots.pdf').

d <- data.frame(matrix(sample(c(1:700), 2000, TRUE), 10, 20))
pdf('plots')
par(mfrow = c(3, 3))  ## set the layout to be 3 by 3
sapply(1:9, function(i) plot(d[,i]))
dev.off()

Which produces this pdf

enter image description here

Rich Scriven
  • 97,041
  • 11
  • 181
  • 245
2

If you want to do this with base graphics, I strongly recommend using the layout() function. It takes a matrix which defines how to split up the window. It will make a row for every row in your matrix and a column for every column. It draws the plots in order of the number of the cells. So if you pass the matrix

#layout(matrix(c(1:7,7), ncol=2, byrow=T))
#     [,1] [,2]
#[1,]    1    2
#[2,]    3    4
#[3,]    5    6
#[4,]    7    7

the first plot will go in the upper left, the second in the upper right, etc, until the 7th plot goes all the way at the bottom. You could just have it take up only the bottom left if you like by specifying a different number in the bottom right.

To reset the layout back to "normal" just call

layout(1)

you could then create a for loop to make each plot.

If you want one plot to do all pairwise comparisons, the pairs() plotting function might be what you want

dd<-matrix(runif(5*5), ncol=5)
pairs(dd)

or the lattice equivalent is splom()

MrFlick
  • 195,160
  • 17
  • 277
  • 295