High-quality R graphics on the Web with SVG

July 7, 2011


If you want the graphics you create with R to look their best, in general it's best to go for a vector-based graphics format instead of a raster-based format. Common formats like GIF and JPG are raster-based: the image is composed of pixels, and if you don't choose a high enough resolution, you're likely to lose fine details and/or the image will look blocky. But if you're publishing on the Web, you're probably limited in resolution (here on the blog, I'm limited to 500px in the horizontal direction, for example). Vector-based formats like PostScript and SVG always look their best regardless of the resolution, because they're rendered on demand from the component lines, symbols, and other elements of your graphic: it's a bit like using a laser printer instead of a dot-matrix printer, with a corresponding increase in quality.

The problem until recently is that not many browsers have had native support for vector images, limiting their usefulness on the web. But now, most modern browsers can render high-quality SVG images using the standard <img> tag, and R can easily [but see note below] generate SVG files with the svg device driver.

For example, here's a calendar heat map of Apple stock since the beginning of 2010 rendered as a SVG:

For comparison, here's the same image rendered as a PNG:

As you can see, the SVG file has much finer detail; this will become even more apparent if you right-click on each image to view them in their own tab, or download AAPL.svg and view it directly. The SVG version (rendered at 14in wide) will show much more detail in larger format. By the way, if you only see one image above it's because your browser doesn't support SVG. (It looks fine on my Mac using recent versions of Chrome and Firefox.) For reference, the above images were created using the following code in R:

calendarHeat(stock.data$Date, stock.data$Adj.Close, 
  varname="AAPL Adjusted Close")
calendarHeat(stock.data$Date, stock.data$Adj.Close, 
  varname="AAPL Adjusted Close")

Created by Pretty R at inside-R.org

Note: your installation of R must have been compiled with "Cairo" support for the svg function to work; you can easily check with the command:

> capabilities()["cairo"]

If it comes back TRUE as above, you're all set. Recent 32-bit MacOS distributions of the MacOS version of R have Cairo support built in, as will the 64-bit MacOS 2.13.1. (I ran the code above using the 2.13.1 MacOS release candidate.) Windows and Linux distributions (including Revolution R) generally don't have Cairo support built in, which you'll have to enable when you build R yourself.




Tags: , ,

Comments are closed.