Getting SVG Graphics to work in R on OS X

I was excited to learn that R supports creating SVG vector images out of the box.  SVG is great because 1) Unlike raster graphics, SVG scales to any size without distortion and 2) The format is XML based and on most modern browsers you can just embed the graphic right into your HTML.  That way you can easily share your R plots on the web — the graphic in this post is indeed SVG.  So you can imagine my dismay when I tried to generate an SVG plot and got this error:

set.seed(1)
x <- 1:10
y <- 1:10 + runif(10)

svg(filename="plot1.svg", width=5, height=5)
  plot(x,y)
dev.off()


Warning messages:
1: In svg(filename = "plot1.svg", width = 5, height = 5) :
unable to load shared object '/Library/Frameworks/R.framework/Resources/library/grDevices/libs//cairo.so':
dlopen(/Library/Frameworks/R.framework/Resources/library/grDevices/libs//cairo.so, 6): Library not loaded: /opt/X11/lib/libXrender.1.dylib
Referenced from: /Library/Frameworks/R.framework/Resources/library/grDevices/libs//cairo.so
Reason: image not found
2: In svg(filename = "plot1.png", width = 5, height = 5) :
failed to load cairo DLL

The problem is OS X Mavericks does not ship with X11 support. Confusingly, this error is actually expected behavior.  A less cryptic message probably could have saved me and you some googling, but at least the fix is easy.  Just install XQuartz and you should be good to go.

Download and install XQuartz:

  1. Go to http://xquartz.macosforge.org/ and download the latest version (2.7.7 when I wrote this)
  2. Mount the .dmg and install the package as usual
  3. After the installation is complete, XQuartz will give you a message telling you to log out and log back in to make XQuartz your default X11 server.  To do so, just click on the Apple icon on the menubar and select “Log Out {Your Username}…” then log back in

Once you’ve logged back in, SVG graphics should work.  Let’s give that another try:
OSX R SVG Plot

The .svg file will output to your working directory, and you can open it with your favorite browser.

4 thoughts on “Getting SVG Graphics to work in R on OS X

  1. Pingback: Fixing a y-axis that is too short in barplot function in R – Peyton Williams

Leave a Reply