Printing high resolution figures from R

I currently make most figures using R with ggplot2 before exporting to other programs which means that they need to be exported in high resolution.

Sometimes I put them directly into a poster and it’s commonly recommended to use vector format, as opposed to raster, so the resolution is high and it will not become pixellated. Vector graphics are infinitely scalable. Common vector format types include pdf, svg, and adobe illustrator (.ai) files.

R only has the svg and pdf options. However, saving R figures in svg or pdf format sometimes caused issues for me when I printed the resulting poster. This includes parts with transparency not being preserved and figures going missing in the final print. The poster printers have told me that sometimes this happens when the resolution of the figure is insufficient. How could this happen? It seems some versions of powerpoint may not keep imported vector images in vector format (see this for example).

Note that when making a figure with the pdf() or svg() functions, you cannot specify resolution directly since they should be vector graphics. However, you can do so with the tiff() command. So I now use a really high resolution tiff format (as in the following code chunk) and it’s worked well when printing to a standard 36x48 inch poster size. The tiff command with a custom file name will initialize a custom plot device. To avoid multiple plots printing to one file, or windows popping up as you make multiple plots, close the plot device after each print.

# initialize a plot device with name "name.tiff" in the directory "output_dir"
# res=300 resolution is usually sufficient
tiff(paste(output_dir,
           name,
           ".tiff", sep=""),
     units="in",width=6, height=5,
     res=300)
# fill this in with the plot command
myplot <- plot(stuff)

# print the plot object to the file that you specified
print(myplot)

# dev.off() # closes only the current plot device
# this command closes all plot devices. 
graphics.off()

Equivalently, you may do this with ggsave. Note ggsave specifies dimensions in units of either “in” (inches), “cm”, “mm”. However the tiff(), jpeg(), pdf() etc. functions assume the dimensions are given in inches. Another difference is that you can specify dpi with ggsave no matter what file extension you are using.

myplot <- plot(stuff)

ggsave(paste(output_dir,
           name,
           ".tiff", sep=""), 
       myplot, width=6, height=5, dpi=300, units="in")
Written on March 1, 2020