LearningR-rcharts
1. rCharts
You can install rCharts from github using the devtools package
require(devtools)
install_github('rCharts', 'ramnathv')
The design philosophy behind rCharts is to make the process of creating, customizing and sharing interactive visualizations easy.
1.1 Getting Started
1.1.1 Create
rCharts uses a formula interface to specify plots, just like the lattice package.
Here are a few examples you can try out in your R console.
First let us load the rCharts package
library(rCharts)
- Polycharts
library(rCharts)
r1 <- rPlot(mpg ~ wt, data = mtcars, type = 'point')
r1
- NVD3
hair_eye = as.data.frame(HairEyeColor)
p2 <- nPlot(Freq ~ Hair, group = 'Eye',
data = subset(hair_eye, Sex == "Female"),
type = 'multiBarChart'
)
p2$chart(color = c('brown', 'blue', '#594c26', 'green'))
p2
- Morris
data(economics, package = "ggplot2")
econ <- transform(economics, date = as.character(date))
m1 <- mPlot(x = "date", y = c("psavert", "uempmed"), type = "Line", data = econ)
m1$set(pointSize = 0, lineWidth = 1)
m1
- Morris
h1 <- hPlot(x = "Wr.Hnd", y = "NW.Hnd",
data = MASS::survey,
type = c("line", "bubble", "scatter"),group = "Clap",size = "Age")
h1
- Rickshaw
usp = reshape2::melt(USPersonalExpenditure)
usp$Var2 <- as.numeric(as.POSIXct(paste0(usp$Var2, "-01-01")))
p4 <- Rickshaw$new()
p4$layer(value ~ Var2, group = "Var1", data = usp, type = "area")
p4$set(slider = TRUE)
p4
- xCharts
require(reshape2)
uspexp <- melt(USPersonalExpenditure)
names(uspexp)[1:2] = c('category', 'year')
x1 <- xPlot(value ~ year, group = 'category', data = uspexp,
type = 'line-dotted')
x1
1.1.2 Share
Any visualization is useful only when you are able to share it. rCharts tries to make it really easy to share the visualizations you create. Let us first create a simple interactive scatterplot to illustrate the different sharing mechanisms built into rCharts.
- Save
- Publish
- Embed
library(rCharts)
r1 <- rPlot(mpg ~ wt, data = mtcars, type = 'point')
- Save
You can save your chart using the save method. The additional parameters passed to the save method determine how the js/css assets of the javascript visualization library are served. You can now email your visualization or embed it in a blog post as an iframe.
# link js/css assets from an online cdn
r1$save('mychart1.html', cdn = TRUE)
# create standalone chart with all assets included directly in the html file
r1$save('mychart2.html', standalone = TRUE)
- Publish
Sometimes, you may want to directly publish the visualization you created, without having to bother with the steps of saving it and then uploading it. rChart has you covered here, and provides a publish method that combines these two steps. It currently supports publishing to RPubs and Gist and I expect to add more providers over time. - Embed
RMarkdown
Suppose you wish to embed a visualization created using rCharts in an Rmd document.
IFrame
One way to do this would be to use the save method to save the chart, and then embed it as an iframe. rCharts saves you the steps by allowing you to use the show method and specify that you want the chart to be embedded as aniframe.
We need to set the chunk options comment = NA and results = "asis" so that the resulting html is rendered asis and not marked up (which is the default in knitr).
{r results = "asis", comment = NA}
r1$show('iframe', cdn = TRUE)
If you have several charts in your Rmd document, you can set these options globally in a setup chunk. Make sure to set cache = F for this chunk so that it is always run.
{r setup, cache = F}
options(rcharts.mode = 'iframe', rcharts.cdn = TRUE)
knitr::opts_chunk$set(results = "asis", comment = NA)
You can now rewrite the earlier sourcecode chunk simply as
r1
I prefer this style when writing, since it allows a user to simply copy paste sourcecode from the html and run it in their R console.
IFrame Inline
The iframe mode requires users to upload the additional chart html files along with their document. This introduces additional steps, and in the case of some providers like Rpubs, is not even possible. Hence, rCharts provides an additional mode named iframesrc that embeds the chart as an inline iframe, which makes your document self contained.
{r results = "asis", comment = NA }
r1$show('iframesrc', cdn = TRUE)
This option has the advantage of keeping the html standalone, but isolating the chart from the html on the page, thereby avoiding css and js conflicts. However, this feature is not supported by IE and Opera.
Inline
A third option to embed an rCharts created visualization is to inline the chart directly. Note that you need to add include_assets = TRUE, only the first time you are creating a chart using a specific library.
{r chart3}
r1$show('inline', include_assets = TRUE, cdn = TRUE)
This approach should work in all browsers, however, it is susceptible to css and js conflicts.
If you are using Slidify to author your Rmd, then you can specify the charting library as ext_widgets in the YAML front matter. Here is a minimal reproducible example.
Note how you did not have to specify include_assets = TRUE. This is because slidify uses the ext_widgets property to automatically pick up the required assets and include them in the header of the resulting html page.
It is easy to embed visualizations created using rCharts into a Shiny application. The main idea is to make use of the utility functions renderChart() and showOutput(). The shiny application created using the code below, can be seen here
## server.r
require(rCharts)
shinyServer(function(input, output) {
output$myChart <- renderChart({
names(iris) = gsub("\\.", "", names(iris))
p1 <- rPlot(input$x, input$y, data = iris, color = "Species",
facet = "Species", type = 'point')
p1$addParams(dom = 'myChart')
return(p1)
})
})
## ui.R
require(rCharts)
shinyUI(pageWithSidebar(
headerPanel("rCharts: Interactive Charts from R using polychart.js"),
sidebarPanel(
selectInput(inputId = "x",
label = "Choose X",
choices = c('SepalLength', 'SepalWidth', 'PetalLength', 'PetalWidth'),
selected = "SepalLength"),
selectInput(inputId = "y",
label = "Choose Y",
choices = c('SepalLength', 'SepalWidth', 'PetalLength', 'PetalWidth'),
selected = "SepalWidth")
),
mainPanel(
showOutput("myChart", "polycharts")
)
))
1.2 Librarys
rCharts supports multiple javascript visualization libraries.
1.2.1 NVD3
NVD3 is an elegant visualization library that provides re-usable chart components based on d3.js. Here is an excerpt
directly taken from the NVD3 website.
“This project is an attempt to build re-usable charts and chart components for d3.js without taking away the power that d3.js gives you. This is a very young collection of components, with the goal of keeping these components very customizeable, staying away from your standard cookie cutter solutions.”
1.2.1.1 CREATE
The NVD3 library supports most of the common chart types.
- Scatter Chart
- Multibar Chart
- Multibar Horizontal Chart
- Pie Chart
- Donut Chart
- Line Chart
- Line with Focus Chart
- Stacked Area Chart
- Multi Chart
You can create an interactive plot making use of the NVD3 library using the nPlot() function.
Argument | Type | Description |
---|---|---|
x | formula | A formula of the form y ~ x, with column names from the data frame. |
data | data frame | A data frame containing the data to be plotted |
type | string | The type of chart to plot |
group | string | Name of column based on which data should be grouped. |
Scatter Chart
p1 <- nPlot(mpg ~ wt, group = 'cyl', data = mtcars, type = 'scatterChart')
p1$xAxis(axisLabel = 'Weight')
p1
Standalone
Multibar Chart
hair_eye = as.data.frame(HairEyeColor)
p2 <- nPlot(Freq ~ Hair, group = 'Eye',
data = subset(hair_eye, Sex == "Female"),
type = 'multiBarChart'
)
p2$chart(color = c('brown', 'blue', '#594c26', 'green'))
p2
Standalone
Multibar Horizontal Chart
Standalone
Pie Chart
p4 <- nPlot(~ cyl, data = mtcars, type = 'pieChart')
p4
Standalone
Donut Chart
p5 <- nPlot(~ cyl, data = mtcars, type = 'pieChart')
p5$chart(donut = TRUE)
p5
Standalone
Line Chart
data(economics, package = 'ggplot2')
p6 <- nPlot(uempmed ~ date, data = economics, type = 'lineChart')
p6
Standalone
Line with Focus Chart
ecm <- reshape2::melt(
economics[,c('date', 'uempmed', 'psavert')],
id = 'date'
)
p7 <- nPlot(value ~ date, group = 'variable',
data = ecm,
type = 'lineWithFocusChart'
)
p7
Standalone
Stacked Area Chart
dat <- data.frame(
t = rep(0:23, each = 4),
var = rep(LETTERS[1:4], 4),
val = round(runif(4*24,0,50))
)
p8 <- nPlot(val ~ t, group = 'var', data = dat,
type = 'stackedAreaChart', id = 'chart'
)
p8
Standalone
Multi Chart
p12 <- nPlot(value ~ date, group = 'variable', data = ecm, type = 'multiChart')
p12$set(multi = list(
uempmed = list(type="area", yAxis=1),
psavert = list(type="line", yAxis=2)
))
p12$setTemplate(script = system.file(
"/libraries/nvd3/layouts/multiChart.html",
package = "rCharts"
))
p12
Standalone
1.3 Visualizing
This tutorial explains in detail, how I used rCharts to replicate this NY times interactive graphic on strikeouts in baseball. The end result can be seen here as a shiny application.