Biostatistics with R

Saving R plots as image files

The functions like plot() or hist() create R plots on the screen. We like to save these plots into standard image formats like PNG, JPEG, TIFF, PDF or PS.


The Cairo package provides a function that can produce high quality image files from R plots. We can convert R plots into high-quality PNG, JPEG, TIFF bitmap files, high resolution PDF files with embedded fonts, SVG graphics and PostScript files. It also provides X11 and Windows interactive graphics devices. Cairo supports important graphics features including alpha blending, anti-aliasing etc.


Cairo has to be installed into R as an external library. To install Cairo once for all, type from R promt,
> install.packages("Cairo")
The package installs into R installation directory. This is a one time installtion.


The important parameters in this function call are described:

file ------> Name of the file to write to type ------> type of file. This value includes "png","jpeg","tiff" for bitmaps, "pdf" for PDF-file, "svg" for SVG-file, "ps" for postscript. units ------> units for the width and height of the plot. "px" (pixels), "in" (inches), "cm"(centimeters), "mm"(millimeters) height -----> height of plot in the specified units. width -----> widthe plot in the specified units. dpi -----> DPI used for converting units to pixels. If set to "auto" the DPI resolution will be determined by the back-end. pointsize -----> initial text size in points.

For other parameters, seek help(Cairo) in R prompt.


After including library(Cairo) , the Cairo function should be called before every plot with specific file name that we want to write the plot into. After plotting, the device should be switched off with dev.off() command. The file is written into directory specified in the path.


In the example script below, we will draw two plots in R and save them into "png" and "jpeg" files using Cairo. After executing the script, we will see the image files "testfile1.png" and "testfile2.jpg" in the present working directory. To write into any other directory, just give the file path along with the file name.


## include Cairo library library(Cairo) ## Initialize the device for saving first plot. ## Plot will have length=500 pixel, width=500 pixel ## saved as a png image file called "testfile1.png" Cairo(file="testfile1.png", type="png", units="px", width=500, height=500, pointsize=12, dpi="auto") ## Now render the plot x = rnorm(10000) hist(x, col="red") ## When the device is off, file writing is completed. dev.off() ## Initialize the device for saving second plot. ## Plot will have length=400 pixel, width=300 pixel ## saved as a png image file called "testfile2.jpg" Cairo(file="testfile2.jpg", type="png", units="px", width=400, height=300, pointsize=12, dpi="auto") ## Now render the plot x = c(1,2,3,4,5,6) y = c(10,20,30,40,50,60) plot(x,y,col="red", type="b") ## When the device is off, file writing is completed. dev.off()