Embedding rCharts

Embedding rCharts in R Markdown

by Ramnath Vaidyanathan, Dec 22, 2003

This is a short note to address a question from Sharon Machlis on the best way to embed a visualization created using rCharts, so that one can create a standalone HTML file using knit2html. If you have not used rCharts, you can try it out using the online playground

You will need the latest version of rCharts (> 0.4) to use the approaches suggested in this note.

library(devtools)
install_github("rCharts", "ramnathv")

Create Chart

Let us first create a simple barplot using NVD3

library(rCharts)
hair_eye_male = subset(as.data.frame(HairEyeColor), Sex == "Male")
n1 <- nPlot(Freq ~ Hair, group = 'Eye', 
  data = hair_eye_male, type = 'multiBarChart'
)
n1$set(width = 600)

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). Make sure to set cache = F for this chunk so that it is always run.

library(knitr)
opts_chunk$set(comment = NA, results = "asis", comment = NA, tidy = F)

Embed Option 1: IFrame Inline

The first option is to embed the chart as an inline iframe. It 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.

n1$show('iframesrc', cdn = TRUE)

Embed Option 2: Inline

This option embeds the chart inline in the html. It should work in all browsers that the charting library being used supports. However, it is susceptible to css and js conflicts.

n1$show('inline', include_assets = TRUE, cdn = TRUE)