Deadlifts and Derivatives

Updates and Research from Steve Bronder

The purpose of this site is to give current information on Steve Bronder's (me) research and personal life

Understanding rCharts

Why use rCharts?

Interactive visualization is the new ‘hot take’ for data people. ggvis and rCharts have become the two easiest ways to make these graphs, but there is a clear difference that needs to be made. rCharts is to ggvis what R is to STATA. They both have the same task. One has a low learning curve and makes it easy to do very simple things while the other has a high learning curve and is made to take on custom projects. When looking at which to use, the drastic differences in learning curves should only be the focus if you have a project due immediately. Otherwise, only the ability to make your life easier in the long run and allow room for growth should be focused on. Throughout this post it will be made clear which makes your life easier in the long run. The purpose of this post is to demonstrate how rCharts works, explain how to find the documentation you need, and show how to export projects to be seen on the web with either a direct link or embedded iframe.

Setting up rCharts and Examples

I would recommend checking out two places to get set up / see examples

  1. The rCharts home page to set up rCharts with devtools

http://ramnathv.github.io/rCharts/

  1. The gallery of rCharts (no longer broken!) has tons of awesome examples and code for making graphs.

http://rcharts.io/gallery/

Look at this gorgeous example of pyramid (histogram) charts in rCharts!

http://walkerke.github.io/2014/06/rcharts-pyramids/

We will use Kyle Walker’s code for this project to go through how rCharts works.

Documetation Woes

You may have noticed that rCharts does not have any documentation. This is true. However, we’ll see quickly it may be due to the fact that documentation is not really necessary. Here’s one secret that people tend to hand wave through, but should stress. ggvis is based off of vega, one particular javascript library that is full of helper functions to write d3 code. ggvis and rCharts both translate your R code into a helper library such as Vega which then translates everything into d3/javascript. This is why rCharts and ggvis need a browser to run!

rCharts can use Vega, along with about nine other libraries for writing d3 code. This makes it much more flexible as you can see from the examples on the rCharts home page. With access to multiple libraries you can use the library that is best suited for the graphic you want to make.

Keep this process in mind throughout the example from the pyramids chart from above.

R -> ‘Some helper library’ -> D3

The code is simple once it is broken down into pieces.

Code Breakdown

h1 sets up the plot for us and is the bread and butter of making rCharts. hPlot uses the Highcharts library to build your interactive visualization like ggvis does with Vega.

  h1 <- hPlot(
    y = 'Population', 
    x = 'Age', 
    type = 'bar', 
    data = dat.melt,
    group = 'Gender')

Alright so hey, that’s simple! We tell R what our x and y variables are, what type of graph, where the data is, and what variable we use to group the data. Lets look at how weird the next line looks and maybe I will blow your mind for a second.

  h1$plotOptions(series = list(stacking = 'normal', pointPadding = 0, borderWidth = 0))

What is this glob of cash signs and lists? The cash sign is used to access variables for what is known as a reference class object like how we can grab our coefficients with mylm$coefficients. It’s pretty similar to a python class if that is easy for you to think about. You can see the reference class for hPlot() here.

So where and how the heck do we find what ‘series’, ‘stacking’, etc. is? Check out the Highcharts API. This is the documentation for the Highcharts library that the R code is being translated into. Remember when we made the type of graph ‘bar’? Look at the link:

http://api.Highcharts.com/Highcharts#series<bar>

Look at that. All of our variables are documented inside of Highcharts for changing the series in a bar chart. So in a way, rCharts has tons of documentation, it’s just written in the libraries. We can look through this and see what stacking, pointpadding, series, etc. stands for. Series contains a list because it has its own parameters to assign. So when you see a parameter in Highcharts that has its own parameters you place those sub-parameters in a list. The reason rCharts has such little documentation is because it would be silly to write all of this stuff twice. Once in rCharts and another time in the actual library. And since rCharts is only translating your R code to this respective library and then to d3 we can just look at the libraries docs for our parameters and variables documentation.

The next line shows where this style of thinking through translating shines. Here we are going to make a tooltip (the thing that shows up when you hover over the chart). The trick is, we are going to write the tooltip in javascript in R.

h1$tooltip(formatter = "#! function() { return '<b>'+ this.series.name +', age '+ this.point.category +'</b><br/>' + 'Population: ' + Highcharts.numberFormat(Math.abs(this.point.y), 0);} !#")

With just a bit of R (calling the correct variable in the reference class) and some javascript, we’ve taken one of the more difficult and impressive things in d3 and made it pretty simple. We create an anonymous function ( function(){ ) and have it return what we would like to see in the tooltip. The whole function is wrapped in a "#! so rCharts knows to take this code and treat is as javascript. We can even throw in some html to get the nice formatting we want.

With some of the knowledge you have now, find the next line in the Highcharts API and figure out what reversed does.

h1$legend(reversed = "true")

With the knowledge of how we use the reference class to access variables and parameters in Highcharts, look at how we change the y axis labels with a javascript function. I leave it to the reader as an exercise to look into the Highcharts API and see what the parameters in yAxis do.

  if (max(dat.melt$Population >= 1000000)) {
    h1$yAxis(labels = list(formatter = "#! function() { return (Math.abs(this.value) / 1000000) + 'M';} !#"), 
             title = list(enabled = TRUE, text = 'Population'))
  } else {
    h1$yAxis(labels = list(formatter = "#! function() { return (Math.abs(this.value) / 1000) + 'K';} !#"), 
             title = list(enabled = TRUE, text = 'Population'))
  }
  
  # Colors is set earlier in his code
  if (!is.null(colors)) {
    h1$colors(colors)
  }
  `

We want people to be able to download the graph as an pdf, svg, etc. so we set exporting to TRUE.

  h1$exporting(enabled = TRUE)

To show the graphic we call the object and a browser should open up.

  h1

And that’s it! Now let’s go over how to show people your work.

Showing Off Your Work

The whole point of making pretty graphs is so other people can see it. One of my biggest complaints about shiny and ggvis is that there are only three ways to present a shiny app / ggvis presentation.

  1. They have R installed and can run your script (lol)
  2. Using shinyapps.io and sending them the link
  3. Having your own shiny server

One is almost never feasible in a business setting and is a pretty tedious process for only viewing a plot. Two and three are both viable, however the free version of shinyapps has a limited time that people are allowed to view the plot. So at some point you will have to fork over cash which I would rather not.

Let’s look at two methods to send an rCharts graphic, either as a html page you can send over email or as a link on gist

Sending an HTML Page

Let’s make a standard rChart from the rCharts page on sharing.

library(rCharts)
r1 <- rPlot(mpg ~ wt, data = mtcars, type = 'point')
r1$show('iframesrc', cdn = TRUE)

Notice in this example the plot goes directly on the page by calling $show(). This post is written in knitr, which allows R code to be written into an html page. The graph is translated into an iframe, which is then placed on the page. To show how to place the graph on a webpage that already exists we call the $save() function and use gist. gist is a sort of ‘one off’ version of git hub. It’s made for sharing code and files quickly and easily which is perfect for our purpose. So first lets save the plot.

r1$set(width = 400, height = 350)
r1$save('C:/Users/brond_000/Documents/Blog/rChartsBreakdown/mychart2.html', standalone = TRUE)

Here we save the plot to a specific folder, and set standalone equal to TRUE so the d3 and Highcharts libraries will be saved inside of the html page the save function generates. Once you save the chart, look in the folder and you should see a html page titled, “mychart2.html”. Clicking that will open up the plot! So now we can send that to someone as an email attachment. Now how do we send them a link? Go to gist and rawgit. When you open up gist you will see a box for code to go into. With the folder open in explorer, drag mychart2 from the folder over onto the box and let go. This will take the code for your plot and place it into the gist box. Now click either create public or secret gist and your code will be stored online! From there click on raw on the right side to go to a page with just your code on it with an address that starts with something like “gist.githubusercontent.com/…”.

Now go to raw git. Inside of the main bar copy/paste the address for your raw gist. Raw git will generate two links, a development and production link. While messing around or just sharing with a friend you can use the development link, but once everything is finalized I would encourage using the production link. Take the development link, paste it into your address bar and take a look at your graph!

Now you can place this graph inside of a webpage with an iframe.

<iframe src="http://cdn.rawgit.com/Stevo15025/c8e37aa1dae84791cdad/raw/0577777b74b980e3cacd66251187650a0c557d8b/mychart2.html"; width=900; height=500; seamless; frameborder=0;></iframe>

And there you have it! Now you can send rCharts to all of your friends and family with ease! In this post we covered how to find variables and parameters for rCharts from a D3 library’s API and how to share visualizations built in rCharts with friends and colleagues. Notice that our embedded iframe cuts off a little bit of the top and right side of our graph. I’ll be exploring why this happens, but for now I do not see this as an issue. If you have any questions feel free to email or leave a comment.