Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Cambridge R user meeting, May 2012
Interactive charts and slides with R, googleVis and knitr
```{r results='asis', echo=FALSE, message=FALSE, tidy=FALSE}
G <- gvisGeoChart(Exports, "Country", "Profit",
options=list(width=250, height=120), chartid="c1")
T <- gvisBarChart(Exports[,1:2], yvar="Profit", xvar="Country",
options=list(width=250, height=260,
legend='none'), chartid="c2")
GT <- gvisMerge(G,T, horizontal=FALSE, chartid="gt")
## Tree map
M <- gvisTreeMap(Regions, "Region", "Parent", "Val", "Fac",
options=list(width=400, height=380,
showScale=TRUE), chartid="c3")
GTM <- gvisMerge(GT, M, horizontal=TRUE,
tableOptions="cellspacing=5", chartid="gtm")
print(GTM, 'chart')
[Markus Gesmann](, [Cambridge R user group]( meeting, 29 May 2012
# Agenda
* Motivation
* Introduction to googleVis
* Examples with googleVis
* How I created this talk with RStudio, knitr, pandoc and slidy
# Motivation
<iframe width="420" height="315" src="" frameborder="0" allowfullscreen></iframe>
* In 2006 Hans Rosling gave an inspiring talk at TED
* He challenged the views and perceptions of many listeners
* To visualise his talk he used animated bubble charts, aka motion charts
# Google Chart Tools
* Google integrated the motion charts into their [Visualisation API]( in 2007
* Google Visulisation API makes it easy to create interactive charts for web pages
* It uses JavaScript and DataTable / JSON as input
* Output is either HTML5/SVG or Flash
* Browser with internet connection required to display chart
* Please read the Google [Terms of Service]( before you start
# Introduction to googleVis
* [googleVis]( is a package for [R]( and provides an interface between R and the [Google Chart Tools](, see *Using the Google Visualisation API with R*,
[The R Journal, 3(2):40-44, December 2011](
* The functions of the package allow users to visualise data with the Google Chart Tools without uploading their data to Google
* The output of googleVis functions is html code that contains the data and references to JavaScript functions hosted by Google
* To view the output a browser with an internet connection is required, the actual chart is rendered in the browser; some charts require Flash
# Key ideas of googleVis
* Create wrapper function in R which generate html files with references to Google's Chart Tools API
* Transform R data frames into [JSON]( objects with [RJSONIO](
cat(toJSON(CityPopularity)) ## example data from googleVis
* Display the HTML output with the R HTTP help server
* Development started in August 2010, intially to visualise data at [Lloyd's](
# googleVis version 0.2.16 provides interfaces to
* Motion Charts
* Annotated Time Lines
* Maps, Geo Maps and Charts
* Intensity Maps
* Tables, Gauges, Tree Maps
* Line-, Bar-, Column-, Area- and Combo Charts
* Scatter-, Bubble-, Candlestick-, Pie- and Org Charts
Run ```demo(googleVis)``` to see [examples]( of all charts and read the [vignette]( for more details.
# [World Bank example](
<iframe height="550px" frameborder="no" scrolling="no"
```{r eval=FALSE}
# Video tutorial
<iframe width="420" height="315" src="" frameborder="0" allowfullscreen></iframe>
* Video tutorial by [Martin Hilpert](, [Freiburg Institute for Advanced Studies](
* Demonstrates how to create motion charts with googleVis
# The googleVis concept
* Charts: *'gvis' + ChartType*
* For a motion chart we have
```{r eval=FALSE}
M <- gvisMotionChart(data, idvar='id', timevar='date', options=list(), chartid)
* Output of googleVis is a list of list
* Display the chart by simply plotting the output ```plot(M)```
* Plot will generate a temporay html-file and open it in a new browser window
* Specific parts can be extracted, e.g. the chart ```M$html$chart``` or data ```M$html$chart["jsData"]```
# Embedding googleVis chart into your web page
Suppose you have an existing web page and would like to integrate the output of a googleVis function, such as ```gvisMotionChart```.
In this case you only need the chart output from ```gvisMotionChart```. So you can either copy and paste the output from the R console
```{r eval=FALSE}
print(M, 'chart') ## or cat(M$html$chart)
into your existing html page, or write the content directly into a file
```{r eval=FALSE}
print(M, 'chart', file='myfilename')
and process it from there.
# Simple line chart
```{r results='asis'}
df <- data.frame(label=c("A", "B", "C"), val1=c(0.10,0.13,0.14), val2=c(23,12,32))
lc <- gvisLineChart(df)
print(lc, 'chart') ## So knitr includes the html output of the chart
# Line chart with options set
```{r results='asis'}
print(gvisLineChart(df, xvar="label", yvar=c("val1","val2"),
options=list(title="Hello World", legend="bottom",
titleTextStyle="{color:'red', fontSize:18}",
vAxis="{gridlines:{color:'red', count:3}}",
hAxis="{title:'My Label', titleTextStyle:{color:'blue'}}",
series="[{color:'green', targetAxisIndex: 0},
{color: 'blue',targetAxisIndex:1}]",
vAxes="[{title:'Value 1 (%)', format:'#,###%'},
{title:'Value 2 (\U00A3)'}]",
curveType="function", width=500, height=300
)), 'chart')
# Chart countries' S&P credit rating
* Plot countries' S&P credit rating sourced from Wikipedia
* See my [blog post]( for more details
## Get and prepare data
url <- ""
page <- readLines(url)
x <- readHTMLTable(page, which=3)
levels(x$Rating) <- substring(levels(x$Rating), 4,
x$Ranking <- x$Rating
levels(x$Ranking) <- nlevels(x$Rating):1
x$Ranking <- as.character(x$Ranking)
x$Rating <- paste(x$Country, x$Rating, sep=": ")
# Chart countries' S&P credit rating
```{r results='asis'}
print(gvisGeoMap(x, "Country", "Ranking", "Rating",
colors="[0x91BFDB, 0XFC8D59]")), 'chart')
# Geo chart with markers
```{r results='asis'}
data(quakes); quakes$latlong<-paste(quakes$lat, quakes$long, sep=":")
print(gvisGeoChart(quakes, locationvar="latlong", colorvar="depth", sizevar="mag",
options=list(displayMode="Markers", region="009",
colorAxis="{colors:['red', 'grey']}",
backgroundColor="lightblue")), 'chart')
# Merging gvis-objects
```{r results='asis'}
G <- gvisGeoChart(Exports, "Country", "Profit", options=list(width=250, height=120))
B <- gvisBarChart(Exports[,1:2], yvar="Profit", xvar="Country",
options=list(width=250, height=260, legend='none'))
M <- gvisMotionChart(Fruits, "Fruit", "Year",options=list(width=400, height=380))
GBM <- gvisMerge(gvisMerge(G,B, horizontal=FALSE),
M, horizontal=TRUE, tableOptions="cellspacing=5")
print(GBM, 'chart')
# Further case studies
* [Statistics Relating to Lloyd's](
* [Analysis of the US domestic airline market from 1999 - 2010](
* [Linguistic analysis of the English language](
* [Exploring the Pen World Data](
* [My blog posts on googleVis](
# Other R packages
* [R animation package allows to create SWF, GIF and MPEG directly](
* [iplots: iPlots - interactive graphics for R](
* [Acinonyx aka iPlots eXtreme](
* [gridSVG: Export grid graphics as SVG](
* [plotGoogleMaps: Plot HTML output with Google Maps API and your own data](
* [RgoogleMaps: Overlays on Google map tiles in R](
# How I created this presentation with RStudio, knitr, pandoc and slidy
* [knitr]( is a package by [Yihui Xie]( that brings literate programming to a new level
* It allows to create content really quickly, without worrying to much about layout and R formatting
* [RStudio]( integrated knitr into its IDE, which allows to knit Rmd-files by the push of a button into markdown
* Markdown output can be converted into serveral other file formats, such as html, with [pandoc](
* [slidy]( is one of the options to create interactive html-slides with pandoc
pandoc -s -S -i -t slidy --mathjax
-o Cambridge_R_googleVis_with_knitr_and_RStudio_May_2012.html
* For more details see my recent [blog post]( and [example file](
* The source file of this presentation is available on [github](
# Conclusion
* Interactive charts and reports open a new way to engage with readers and users, who would find data and figures boring otherwise
* RStudio, *knitr* and googleVis might be the way forward to create interactive analysis reports and presentations
* The markdown language should be sufficient for most tasks to draft a report, and the integration with RStudio makes it a pleasure to work with *knitr*.
# Thanks to ...
* Google for making the Chart Tools available
* My co-author Diego de Castillo
* [All who have provided ideas, feedback, bug reports, suggestions, etc.](
* [Yihui Xie]( for [knitr](
* JJ, Joe and Josh for [RStudio](
* [Dave Raggett]( for [Slidy](
# Contact
* googleVis: [](
* My blog: [](
* Email: markus dot gesmann at gmail dot com

This comment has been minimized.

Copy link

@nksingh62 nksingh62 commented Jun 25, 2015

Getting error in line 66 in running from Rstudio (version .99) on R 3.2.0

cat(toJSON(CityPopularity)) ## example data from googleVis

could not find toJSON call withCallingHandlers->withVisible_> eval->eval->cat

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment