pdf, png, dev.off

Initialize a plot that will be written directly to a file using pdf or png. Then create a plot using the usual functions in R. Finally, close the file using the dev.off function. There are also bmp, tiff, and jpeg functions, though the jpeg function has proven less stable than the others.
pdf(filename, width=7, height=7)
  • filename – A character string for the file name, ending in .pdf.
  • width – Width of the image, in inches.
  • width – Height of the image, in inches.
png(filename, width=480, height=480)
  • filename – A character string for the file name, ending in .png.
  • width – Width of the image, in inches.
  • width – Height of the image, in inches.
dev.off()

Example. The code below shows two examples of saving a scatterplot with a regression line to a file.
> set.seed(1)
> x <- 1:100
> y <- 0.029*x + rnorm(100)
> 
> pdf("sample.pdf", 7, 5)
> plot(x, y, pch=19, col=rgb(0.5, 0.5, 0.5, 0.5), cex=1.5)
> abline(lm(y ~ x))
> dev.off()
null device 
          1 
> 
> png("sample.png", 490, 350)
> plot(x, y, pch=19, col=rgb(0.5, 0.5, 0.5, 0.5), cex=1.5)
> abline(lm(y ~ x))
> dev.off()
null device 
          1 

Tip. By default, PDF files may have more than one page. Simply create additional plots before closing the figure file (via dev.off), and these additional figures will be written to their own page. (This option will not work for other types of figure files.)
Tip. To specify plotting parameters, use par after initializing the file via pdf, png, or another figure file creation function.
Tip. Saving plots directly to files is a useful strategy for work that is being shared or published. This approach makes it easy to share code with others who want to recreate figures exactly. Researchers who want to make reproducible results that make use of random numbers should also see set.seed.
Tip. The dev.off function may also be used to close open plotting windows.

Leave a Reply