a reproducible gallery of statistical graphics
D3 is a popular JavaScript library to draw graphics on the web. Powerful as it is, I often feel it is limited to me as a statistician, especially a statistician spoiled by R – in which I can draw plots without thinking of primitives such as points, lines, segments and so on, and all kinds of statistical functions are there for me to call. In this article I explain how to combine R and D3 to draw a contour plot.
The computation of contour lines can be challenging to JavaScript but is extremely easy with R
using the contourLines()
function, so we pre-process the data and make it ready to JavaScript. We
make use of the good old volcano
dataset here and draw a contour plot to visualize the altitude
corresponding to a grid of latitudes and longitudes (the picture above of the volcano is from
Wikipedia).
We can see the results returned by contourLines()
is a list of sub-lists: each sub-list contains
the x-y coordinates of polylines. Now we convert this list to a JSON array of the form:
And write the data to a script
tag:
Now we are ready to call D3 to draw all the lines (see the HTML source code of this page):
This is indeed a plot drawn by D3; if you do not believe it, mouse over the lines and you will see them highlighted in yellow, or refresh this page to see line width transition from 0 to 2.
With R, it is just one line of code but it is a static plot (not interactive):
It is rare that we solve a problem with a single tool. Take the advantages of all tools instead of
blindly believing that one ring will rule them all. R is good for statistical computing and
graphics, and D3 is awesome for the web. Both are good in one way but weak in another, so let’s
make 1 + 1 > 2
.