Uniform R code for opening, saving graphs in Windows and Mac OS

January 18, 2013
By

(This article was originally published at Doing Bayesian Data Analysis, and syndicated at StatsBlogs.)

A big frustration when trying to create R code for users of both Windows and Mac OS is that the R commands for opening graphics windows, and for saving their contents, are different in the two operating systems. In Windows, the functions windows() and savePlot() do the job nicely. But in Mac OS, equivalent commands are X11(,type="cairo") and either savePlot() or dev.copy2* depending on the desired format.

In this post I present two simple utility functions for opening graphics windows and saving them that operate the same for Windows and Mac OS. (You'd think someone would have done this already, but it appears not?) The basic sequence of commands is this:

openGraph(...)  # open a graphics window
plot(...)       # create graph in the window
saveGraph(...)  # save to a file in desired format

I have tested the functions on recent Windows and Mac OS machines, running from RStudio desktop. I would like to know if users encounter problems with the functions when running in a different configuration. Also, I doubt that the functions work on Linux, but perhaps Linux users out there could comment with suggested expansions/changes to the functions to accommodate Linux too.

Here is an R script that defines the functions and then calls them with several different file formats. Please copy and paste the entire script into R and give it a try. Let me know how it goes.

#------------------------------------------------------------------------

openGraph <- function( width=7 , height=7 , ... ) {
  if ( .Platform$OS.type != "windows" ) {
    X11( width=width , height=height , type="cairo" , ... ) # for Mac OS
  } else { # if Windows OS
    windows( width=width , height=height , ... )
  }
}

saveGraph <- function( file="saveGraphOutput" , type="pdf" , ... ) {
  if ( .Platform$OS.type != "windows" ) {
    if ( any( type == c("png","jpg","jpg","tiff","bmp")) ) {
      if ( type == "jpg" ) { sptype="jpeg" }
      savePlot( file=paste(file,".",type,sep="") , type=sptype )     
    }
    if ( type == "pdf" ) {
      dev.copy2pdf(file=paste(file,".",type,sep=""))
    }
    if ( type == "eps" ) {
      dev.copy2eps(file=paste(file,".",type,sep=""))
    }
  } else { # if Windows OS
    savePlot( file=file , type=type , ... )
  }
}

graphics.off()
for ( typeVal in c("eps","pdf","jpg","jpeg","png") ) {
  openGraph(width=3,height=3)
  plot(1:4,c(1,3,2,4),type="o",main=bquote(typeVal==.(typeVal)))
  saveGraph( file="openGraphSaveGraphOutput", type=typeVal )
}
 

#------------------------------------------------------------------------



Please comment on the article here: Doing Bayesian Data Analysis


Subscribe

Email:

  Subscribe