R + D3, A powerful and beautiful combo

For a while now, I have been looking for ways to incorporate pretty D3 graphics into R markdown reports or shiny apps. Why? I like R for the ability to be able to do data handling, stats, ML all very easily with minimal code. But when you want to present something to clients or the public, there is no competition for the front end web stuff e.g. d3.js. The answer: htmlwidgets.

Ok well I wasn’t looking too hard because it completely escaped me that you could do this with htmlwidgets. I stumbled upon this when I was browsing the shiny user showcase and I came across the FRISS Analytics example which is accompanied by a really fantastic set of tutorials under ‘other tutorials’. If you want to do this to customise for your own plotting needs, I strongly suggest you start there with those tutorials. They are very thourough and step-wise and will allow you to build a R-D3 binding for the first time with very little hassle, as I have done.

It looks a little like this…

You write a package.

The package contains R functions.

Those functions invoke JavaScript as you define it.

htmlwidgets binds them together and provide the plumbing between your R objects and the JavaScript that you feed them into.

The outcome is that you can easily create an interactive graphic in the end my simply calling an R function. The real beauty though is being able to update the javascript plot in response to user input on the R side, without plotting a new plot each time in the slightly awkward way that I was previously doing. If you have loaded the app try typing extra zeros into the sample size, you’ll see the plot update as the underlying data is updated. Smooth. This is what I was looking for.

Of course you don’t need to be a JavaScript programmer to get this done. You can use higher levels js libraries such as C3 in my case or nvd3, maybe there are more?

So all in all the chain is…

R -> htmlwidgets -> || C3 -> D3 -> JavaScript.

Where htmlwidgets is reaching through the border between R and JavaScript.

I forked the R package from FRISS and when I get some time or there is a need, I will try to port some more C3 based templates and expose them to R functions in this way.