Monday, January 12, 2015

Making repeatable figures in R

Of course when you code out a figure in R, you can run the code again and get the figure again.  However, I've been just using plot() or whatever variation and then sizing the picture when I export it from RStudio.  This method isn't very repeatable with regards to the size of the plot area.  You can specify pixel sizes and the file name in RStudio's export window as well, which is fine just once, but annoying after finding tiny problems with the figure a dozen times in a row.  Plus, hypothetically, sometimes one's paper gets rejected and one needs to re-do just one figure, but then it won't match the sizes of the remaining figures without much searching about for dimensions.  Just hypothetically, of course.  Anyway, with all this in mind, I put some time into learning how to use the print to device functions where width and height is specified in the code.

  "x"=c(rnorm(n=10, mean=1, sd=0.5)),
  "y"=c(rnorm(n=10, mean=2, sd=1))

#The files are written to your working directory, so set that:
#Replace this with your working folder path.

#First, we'll do a vector format called eps.

my.width<-8 #eps() and svg() (another vector format, code below) use inches.
#I want my plot's height/width ratio to match these dimensions
#which were given in pixels by a journal's instructions to authors.

#If you don't have Adobe Illustrator, install first GPL Ghostscript and then GSView to view this file.
#R will make the file correctly regardless (I tested this on a computer without Ghostscript
# then viewed it on another computer with Ghostscript and GSView, and it wrote the file correctly.
#I will post more information on working with .eps next week.

#I've also used another vector format called svg.
#You can use a free program called Inkscape to edit and add in additional graphics.

svg(file="testing.svg", width=my.width, height=my.height)

#png() make a raster file by default with measurements in pixels instead of inches.
png(file="testing.png", width=129, height=174)
#I'm not sure why but I needed to use this here instead of
#When I used just I got a sharing violation error when trying to open the png.

#In help you can see that other raster formats available as well: bmp(), jpeg(), and tiff().
#The help file also says that we can use units= to change the units to inches ("in"),
#millimeters ("mm"), or centimeters ("cm") instead of the default pixels ("px").

No comments:

Post a Comment

Comments and suggestions welcome.