Interactive charts with googleVis in R

Tokyo R User Group, 17 April 2014

Markus Gesmann
Maintainer and co-author of googleVis



  1. I am an autodidact
  2. What I present here works for me
  3. Read and follow the official Google Chart API documentation and Terms of Service
  4. Sometimes you have to re-load this presentation for the charts and all slides to appear


  • Introduction and motivation
  • Google Chart Tools
  • R package googleVis
    • Concepts of googleVis
    • Recent developments

Introduction and motivation

Hello, I am Markus Gesmann

I work here: Lloyd's of London

The leading specialty insurance market

Hans Rosling: No more boring data

Motivation for googleVis

  • Inspired by Hans Rosling’s talks we wanted to use interactive data visualisation tools to foster the dialogue between data analysts and others
  • We wanted moving bubbles charts as well
  • The software behind Hans’ talk was bought by Google and integrated as motion charts into their Visualisation API
  • Ideally we wanted to use R, a language we knew
  • Hence, we had to create an interface between the Google Chart Tools and R

Google Chart Tools

Introduction to Google Chart Tools

  • Google Chart Tools provide a way to visualize data on web sites
  • The API makes it easy to create interactive charts
  • 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

Structure of Google Charts

The chart code has five generic parts:

  1. References to Google's AJAX and Visualisation API
  2. Data to visualize as a DataTable
  3. Instance call to create the chart
  4. Method call to draw the chart including options
  5. HTML <div> element to add the chart to the page

How hard can it be?

  • Transform data into JSON object
  • Wrap some HTML and JavaScript around it
  • Thus, googleVis started life in August 2010

Motion chart example

plot(gvisMotionChart(Fruits, "Fruit", "Year",
                     options=list(width=600, height=400)))

R package googleVis

Overview of googleVis

  • googleVis is a package for R and provides an interface between R and the Google Chart Tools

  • The functions of the package allow users to visualize 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

  • See also: Using the Google Visualisation API with R, The R Journal, 3(2):40-44, December 2011 and googleVis package vignette

googleVis version 0.5.1 provides interfaces to

  • Flash based
    • Motion Charts
    • Annotated Time Lines
    • Geo Maps
  • HMTL5/SVG based
    • Maps, Geo Charts and Intensity Maps,
    • Tables, Gauges, Tree Maps, Timelines,
    • Line-, Bar-, Column-, Area- and Combo Charts,
    • Scatter-, Bubble-, Candlestick-, Pie- and Org Charts,
    • Annotation-, Calendar-, Histogram and Sankey Charts
  • Support for roles and trendlines

Run demo(googleVis) to see examples of all charts and read the vignette for more details.

Key ideas of googleVis

  • Create wrapper functions in R which generate html files with references to Google's Chart Tools API
  • Transform R data frames into JSON objects with RJSONIO
dat <- data.frame(x = LETTERS[1:2], y = 1:2)
## {
##  "x": [ "A", "B" ],
## "y": [ 1, 2 ] 
## }
  • Display the HTML output with the R HTTP help server

The googleVis concept

  • Charts: 'gvis' + ChartType
  • For a motion chart we have
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 temporary 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"]

gvis-Chart structure

List structure:

gvis object structure

Scatter chart

df <- data.frame(year=1:11, x=1:11)

Add additional columns to define roles - NEW

df <- data.frame(year=1:11, x=1:11,
                 x.scope=c(rep(TRUE, 8), rep(FALSE, 3)),
                 y=11:1, y.html.tooltip=LETTERS[11:1],                 
                 y.certainty=c(rep(TRUE, 5), rep(FALSE, 6)),
                 y.emphasis=c(rep(FALSE, 4), rep(TRUE, 7)))

Line chart with options set

df <- data.frame(label=c("US", "GB", "BR"), val1=c(1,3,4), val2=c(23,12,32))
Line <- 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                         

Options in googleVis have to follow the Google Chart API options

Line chart with options


Displaying geographical information

Plot countries' S&P credit rating sourced from Wikipedia

url <- ""
x <- readHTMLTable(readLines(url), 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=": ")
G <- gvisGeoChart(x, "Country", "Ranking", hovervar="Rating",
                             colorAxis="{colors:['#91BFDB', '#FC8D59']}"))

Chart countries' S&P credit rating


Geo chart with markers

Display earth quakes in Japan of last 30 days

eq <- read.csv("")
eq$loc=paste(eq$Latitude, eq$Longitude, sep=":")

G <- gvisGeoChart(eq, "loc", "Depth", "Magnitude",
                   colorAxis="{colors:['purple', 'red', 'orange', 'grey']}", 

Geo chart of earth quakes


Google Map - NEW individual markers

df <- data.frame(Adress=c("EC3M 7HA", "東京都新宿区北新宿2-21-1"),
                 Tip=c("Lloyd's", "Tokyo R User Group"))
plot(gvisMap(df, "Adress", "Tip",
                icons="{'default': {'normal': '',
                                               'selected': ''}
                                  }", width=800, height=250)))

Timeline - NEW

dat <- data.frame(Room=c("Room 1","Room 2","Room 3"),
                  Language=c("Japanese", "English", "German"),
                  start=as.POSIXct(c("2014-04-17 14:00", "2014-04-17 15:00",
                                     "2014-04-17 14:30")),
                  end=as.POSIXct(c("2014-04-17 15:00", "2014-04-17 16:00",
                                   "2014-04-17 15:30")))
plot(gvisTimeline(data=dat, rowlabel="Room", barlabel="Language",
                  start="start", end="end", options=list(width=800, height=250)))

Sankey chart - NEW

dat <- data.frame(From=c(rep("A",3), rep("B", 3)), 
                  To=c(rep(c("X", "Y", "Z"),2)),
plot(gvisSankey(dat, from="From", to="To", weight="Weight",

Calendar chart - NEW

plot(gvisCalendar(Cairo, datevar="Date",
                  options=list(calendar="{ cellSize: 10 }"))

Annotation Chart - NEW

xtable(tail(Stock, 3))
Date Device Value Title Annotation
10 13882.00 Pens 14334.00 Out of stock Ran out of stock of pens at 4pm
11 13883.00 Pens 66467.00
12 13884.00 Pens 39463.00
A <- gvisAnnotationChart(Stock, datevar="Date",
                         numvar="Value", idvar="Device",
                         titlevar="Title", annotationvar="Annotation",
                                      width=600, height=300)

Annotation Chart - NEW

plot(A, tag='chart')

Merging gvis-objects

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")

Display merged gvis-objects


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

print(M, "chart")  #### or cat(M$html$chart)

into your existing html page, or write the content directly into a file

print(M, "chart", file = "myfilename")

and process it from there.

Embedding googleVis output via iframe

  • Embedding googleVis charts is often easiest done via the iframe tag:
  • Host the googleVis output on-line, e.g. public Dropbox folder
  • Use the iframe tag on your page:
<iframe width=620 height=300 frameborder="0"
Your browser does not support iframe

iFrame output

Including googleVis output in knitr with plot statement

  • With version 0.3.2 of googleVis plot.gvis gained the argument 'tag', which works similar to the argument of the same name in print.gvis.

  • By default the tag argument is NULL and plot.gvis has the same behaviour as in the previous versions of googleVis.

  • Change the tag to 'chart' and plot.gvis will produce the same output as print.gvis.

  • Thus, setting the gvis.plot.tag value to 'chart' in options() will return the HTML code of the chart when the file is parsed with knitr.

  • See the example in ?plot.gvis for more details

Further reading and examples

The End. Questions?

How I created these slides

## Edit the file index.Rmd file and then

Other R packages


  • Google, who make the visualisation API available
  • All the guys behind and Hans Rosling for telling everyone that data is not boring
  • Sebastian Perez Saaibi for his inspiring talk on 'Generator Tool for Google Motion Charts' at the R/RMETRICS conference 2010
  • Henrik Bengtsson for providing the 'R.rsp: R Server Pages' package and his reviews and comments
  • Duncan Temple Lang for providing the 'RJSONIO' package
  • Deepayan Sarkar for showing us in the lattice package how to deal with lists of options
  • Paul Cleary for a bug report on the handling of months: Google date objects expect the months Jan.- Dec. as 0 - 11 and not 1 - 12.
  • Ben Bolker for comments on plot.gvis and the usage of temporary files


  • John Verzani for pointing out how to use the R http help server
  • Cornelius Puschmann and Jeffrey Breen for highlighting a dependency issue with RJONSIO version 0.7-1
  • Manoj Ananthapadmanabhan and Anand Ramalingam for providing ideas and code to animate a Google Geo Map
  • Rahul Premraj for pointing out a rounding issue with Google Maps
  • Mike Silberbauer for an example showing how to shade the areas in annotated time line charts
  • Tony Breyal for providing instructions on changing the Flash security settings to display Flash charts locally
  • Alexander Holcroft for reporting a bug in gvisMotionChart when displaying data with special characters in column names
  • Pat Burns for pointing out typos in the vignette


  • Jason Pickering for providing a patch to allow for quarterly and weekly time dimensions to be displayed with gvisMotionChart
  • Oliver Jay and Wai Tung Ho for reporting an issue with one-row data sets
  • Erik Bülow for pointing out how to load the Google API via a secure connection
  • Sebastian Kranz for comments to enhance the argument list for gvisMotionChart to make it more user friendly
  • Sebastian Kranz and Wei Luo for providing ideas and code to improve the transformation of R data frames into JSON code
  • Sebastian Kranz for reporting a bug in version 0.3.0
  • Leonardo Trabuco for helping to clarify the usage of the argument state in the help file of gvisMotionChart
  • Mark Melling for reporting an issue with jsDisplayChart and providing a solution


  • Joe Cheng for code contribution to make googleVis work with shiny
  • John Maindonald for reporting that the WorldBank demo didn't download all data, but only the first 12000 records.
  • Sebastian Campbell for reporting a typo in the Andrew and Stock data set and pointing out that the core charts, such as line charts accept also date variables for the x-axis.
  • John Maindonald for providing a simplified version of the WorldBank demo using the WDI package.
  • John Muschelli for suggesting to add 'hovervar' as an additional argument to gvisGeoChart.
  • Jacqueline Buros for providing code to include formats parameter to gvisTable()
  • JJ Allaire for pointing out how to use the viewer pane in RStudio o Oliver Gjoneski and Ashton Trey Belew for patches on roles and tooltips
  • Ramnath Vaidyanathan for slidify.

Session Info

## R version 3.1.0 (2014-04-10)
## Platform: x86_64-apple-darwin13.1.0 (64-bit)
## locale:
## [1] en_GB.UTF-8/en_GB.UTF-8/en_GB.UTF-8/C/en_GB.UTF-8/en_GB.UTF-8
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## other attached packages:
## [1] xtable_1.7-3    XML_3.98-1.1    RJSONIO_1.0-3   slidify_0.4    
## [5] googleVis_0.5.1
## loaded via a namespace (and not attached):
## [1] digest_0.6.4   evaluate_0.5.3 formatR_0.10   knitr_1.5     
## [5] markdown_0.6.5 stringr_0.6.2  tools_3.1.0    whisker_0.3-2 
## [9] yaml_2.1.11