Interactive Controls and rCharts

by Ramnath Vaidyanathan, Dec 25, 2013


There was a recent blog post by Sheri Gilley of Revolution Analytics on Combining the Power of DeployR, rCharts, and AngularJS. It is a very cool application that showcases the power of R and Revolution R Enterprise, in being able to integrate frameworks like rCharts and AngularJS. Although I haven't had the opportunity to play with DeployR, I believe that along with Shiny and OpenCPU, it presents a bright future for building and deploying interactive R applications on the web.

Now, what some of you may not know is that integration of simple interactive controls using AngularJS and DatGUI has been available in rCharts for quite some time now. The nice thing about using a framework like AngularJS is that a lot of the interactivity can be handled on the client side with minimal amount of code, after the chart has been created from R.

Let us start by creating a simple scatterplot of mileage vs weight of cars from the ubiquitous mtcars dataset.

library(rCharts)
n1 <- rPlot(mpg ~ wt, data = mtcars, color = "gear", type = "point")
n1

Suppose, we want to let the user choose the x, y and color variables interactively. This can be done using the addControls method, which accepts three arguments: (1) the variable to control, (2) it's current value and (3) the possible set of values to choose from. By default, addControls uses AngularJS to add the controls.

n1$addControls("x", value = "wt", values = names(mtcars))
n1$addControls("y", value = "wt", values = names(mtcars))
n1$addControls("color", value = "gear", values = names(mtcars))
n1

See how a few lines of R code can result in a nice visualization with interactive controls. Cool, right!

Let us build another chart with interactive controls, this time using the NVD3 library for the chart and the DatGUI javascript library for interactive controls. As before, the code stays almost the same, except that we swap the controls template to use datgui instead of angularjs.

HairEye <- subset(as.data.frame(HairEyeColor), Sex == "Male")
n1 <- nPlot(Freq ~ Eye, data = HairEye, group = 'Hair', type = 'multiBarChart')
n1$addControls("type", "multiBarChart", 
  values = c('multiBarChart', 'multiBarHorizontalChart')
)
n1$setTemplate(script = system.file('libraries', 'nvd3', 'controls', 'datgui.html', package = 'rCharts'))
n1$set(width = 650)
n1

Currently, rCharts only supports simple controls, and my plan is to extend this support. In my next post, I will discuss how rCharts can integrate with a server side framework like Shiny or OpenCPU to allow for greater level of interactivity, that might involve more extensive manipulation of data.

Fork me on GitHub