-
Notifications
You must be signed in to change notification settings - Fork 30
/
index.Rmd
550 lines (395 loc) · 17.3 KB
/
index.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
---
title : Introduction to googleVis
subtitle : Lancaster University, 21 May 2013
author : Markus Gesmann
job : Maintainer of the googleVis and ChainLadder packages
framework : io2012 # {io2012, html5slides, shower, dzslides, ...}
highlighter : highlight.js # {highlight.js, prettify, highlight}
hitheme : tomorrow #
widgets : [] # {mathjax, quiz, bootstrap}
mode : selfcontained # {standalone, draft}
license : by-nc-sa
github :
user : mages
repo : Introduction_to_googleVis
---
## Disclaimer
1. I am an autodidact
2. What I present here works for me
3. Read and follow the official [Google Chart API documentation](https://developers.google.com/chart/) and [Terms of Service](https://developers.google.com/readme/terms)
4. Sometimes you have re-load this presentation for the charts and all slides to appear
---
## Agenda
* Introduction and motivation
* Google Chart Tools
* R package googleVis
* Concepts of googleVis
* Case studies
```{r setOptions, echo=FALSE}
options(gvis.plot.tag="chart")
```
--- .class #id
## Hans Rosling: No more boring data
<iframe width="420" height="315" src="http://www.youtube.com/embed/hVimVzgtD6w" frameborder="0" allowfullscreen></iframe>
---
## 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
---
## Overview of googleVis
* [googleVis](http://code.google.com/p/google-motion-charts-with-r/) is a package for [R](http://www.r-poject.org/) and provides an interface between R and the [Google Chart Tools](https://developers.google.com/chart/)
* 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
* See also: **Using the Google Visualisation API with R**,
[The R Journal, 3(2):40-44, December 2011](http://journal.r-project.org/archive/2011-2/RJournal_2011-2_Gesmann+de~Castillo.pdf) and googleVis [package vignette](http://cran.r-project.org/web/packages/googleVis/vignettes/googleVis.pdf)
---
## 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](https://developers.google.com/terms/) 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 visualise 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
```{r motionchartcode, results='asis'}
library(googleVis)
plot(gvisMotionChart(Fruits, "Fruit", "Year",
options=list(width=600, height=400)))
```
---
## googleVis version 0.4.2 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
* Line-, Bar-, Column-, Area- and Combo Charts
* Scatter-, Bubble-, Candlestick-, Pie- and Org Charts
Run ```demo(googleVis)``` to see [examples](http://code.google.com/p/google-motion-charts-with-r/wiki/GadgetExamples) of all charts and read the [vignette](http://cran.r-project.org/web/packages/googleVis/vignettes/googleVis.pdf) 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](http://www.json.org/) objects with [RJSONIO](http://www.omegahat.org/RJSONIO/)
```{r}
library(RJSONIO)
dat <- data.frame(x=LETTERS[1:2], y=1:2)
cat(toJSON(dat))
```
* Display the HTML output with the R HTTP help server
---
## The googleVis concept
* Charts: *'gvis' + ChartType*
* For a motion chart we have
```{r eval=FALSE, tidy=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 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:
<img height=350 src="https://dl.dropbox.com/u/7586336/googleVisExamples/gvisObject.png" alt="gvis object structure" />
---
## Line chart with options set
```{r results='asis', tidy=FALSE}
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
```{r results='asis'}
plot(Line)
```
---
## On-line changes
You can enable the chart editor which allows users to change the chart.
```{r results='asis'}
plot(gvisLineChart(df, options=list(gvis.editor="Edit me!", height=350)))
```
---
## Change motion chart settings
```{r results='asis'}
plot(gvisMotionChart(Fruits, "Fruit", "Year",
options=list(width=500, height=350)))
```
Change displaying settings via the browser, then copy the state string from the 'Advanced' tab and set to `state` argument in `options`.
Ensure you have newlines at the beginning and end of the string.
---
## Motion chart with initial settings changed
```{r results='asis', tidy=FALSE}
myStateSettings <- '\n{"iconType":"LINE", "dimensions":{
"iconDimensions":["dim0"]},"xAxisOption":"_TIME",
"orderedByX":false,"orderedByY":false,"yZoomedDataMax":100}\n'
plot(gvisMotionChart(Fruits, "Fruit", "Year",
options=list(state=myStateSettings, height=320)))
```
---
## Displaying geographical information
Plot countries' S&P credit rating sourced from Wikipedia (requires googleVis 0.4.3)
```{r tidy=FALSE}
library(XML)
url <- "http://en.wikipedia.org/wiki/List_of_countries_by_credit_rating"
x <- readHTMLTable(readLines(url), which=3)
levels(x$Rating) <- substring(levels(x$Rating), 4,
nchar(levels(x$Rating)))
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",
options=list(gvis.editor="S&P",
colorAxis="{colors:['#91BFDB', '#FC8D59']}"))
```
---
## Chart countries' S&P credit rating
```{r results='asis'}
plot(G)
```
---
## Geo chart with markers
Display earth quake information of last 30 days
```{r results='asis', tidy=FALSE}
library(XML)
eq <- read.csv("http://earthquake.usgs.gov/earthquakes/feed/v0.1/summary/2.5_week.csv")
eq$loc=paste(eq$Latitude, eq$Longitude, sep=":")
G <- gvisGeoChart(eq, "loc", "Depth", "Magnitude",
options=list(displayMode="Markers",
colorAxis="{colors:['purple', 'red', 'orange', 'grey']}",
backgroundColor="lightblue"), chartid="EQ")
````
---
## Geo chart of earth quakes
```{r results='asis', tidy=FALSE}
plot(G)
```
---
## Org chart
```{r results='asis', tidy=FALSE}
Org <- gvisOrgChart(Regions, options=list(width=600, height=250,
size='large', allowCollapse=TRUE))
plot(Org)
```
---
## Org chart data
```{r}
Regions
```
Notice the data structure. Each row in the data table describes one node. Each node (except the root node) has one or more parent nodes.
---
## Tree map
Same data structure as for org charts required.
```{r results='asis'}
Tree <- gvisTreeMap(Regions, idvar="Region", parentvar="Parent",
sizevar="Val", colorvar="Fac",
options=list(width=450, height=320))
plot(Tree)
```
---
## Annotated time line data
Display time series data with notes.
```{r}
head(Stock)
```
---
## Annotated time line
```{r results='asis', eval=FALSE}
A1 <- gvisAnnotatedTimeLine(Stock, datevar="Date",
numvar="Value", idvar="Device",
titlevar="Title", annotationvar="Annotation",
options=list(displayAnnotations=TRUE,
legendPosition='newRow',
width=600, height=300), chartid="ATLC"
)
plot(A1)
```
<iframe src="https://dl.dropboxusercontent.com/u/7586336/googleVisExamples/AnnotatedTimeLineExample.html" frameborder="0", width="620", height="350">Loading</iframe>
---
## Merging gvis-objects
```{r results='asis', tidy=FALSE}
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
```{r merged, results='asis', eval=FALSE}
plot(GBM)
```
<iframe src="https://dl.dropboxusercontent.com/u/7586336/googleVisExamples/gvisMergeExample.html" frameborder="0", width="620", height="420">Loading</iframe>
---
## 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.
---
## 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"
src="http://dl.dropbox.com/u/7586336/RSS2012/line.html">
Your browser does not support iframe
</iframe>
```
---
## iFrame output
<iframe width=620 height=300 frameborder="0" src="http://dl.dropbox.com/u/7586336/RSS2012/line.html">You browser does not support iframe</iframe>
---
## 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
---
## Blog articles with googleVis tips
* [How to set axis options in googleVis](http://lamages.blogspot.co.uk/2013/04/how-to-set-axis-options-in-googlevis.html)
* [World Bank data demo](http://lamages.blogspot.co.uk/2013/03/googlevis-042-with-support-for-shiny.html)
* [First steps of using googleVis on shiny](http://lamages.blogspot.co.uk/2013/02/first-steps-of-using-googlevis-on-shiny.html)
* [Using googleVis with knitr](http://lamages.blogspot.co.uk/2012/10/googlevis-032-is-released-better.html)
* [Rook rocks! Example with googleVis](http://lamages.blogspot.co.uk/2012/08/rook-rocks-example-with-googlevis.html)
* [Plotting share price data](http://lamages.blogspot.co.uk/2012/02/reshaping-world.html)
---
## Other R packages
* [R animation package allows to create SWF, GIF and MPEG directly](http://animation.yihui.name/)
* [iplots: iPlots - interactive graphics for R](http://cran.r-project.org/web/packages/iplots/)
* [Acinonyx aka iPlots eXtreme](http://rforge.net/Acinonyx/index.html)
* [gridSVG: Export grid graphics as SVG](http://cran.r-project.org/web/packages/gridSVG/index.html)
* [plotGoogleMaps: Plot HTML output with Google Maps API and your own data](http://cran.r-project.org/web/packages/plotGoogleMaps/)
* [RgoogleMaps: Overlays on Google map tiles in R](http://cran.r-project.org/web/packages/RgoogleMaps/index.html)
* [rCharts](http://ramnathv.github.io/rCharts/)
* [clickme](https://github.com/nachocab/clickme)
---
## How I created these slides
```{r slidify, eval=FALSE}
library(slidify)
setwd("~/Dropbox/Lancaster/")
author("Introduction_to_googleVis")
## Edit the file index.Rmd file and then
slidify("index.Rmd")
```
---
## The End. So what ...?
* googleVis brings interactive plots to R
* Use them to engage with other
* No more boring data
----
## Contact
* Markus Gesmann
* [markus.gesmann gmail.com](mailto:[email protected])
* My blog: [http://lamages.blogspot.com](http://lamages.blogspot.com)
---
## Thanks
* Google, who make the visualisation API available
* All the guys behind www.gapminder.org 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
---
## Thanks
* 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
---
## Thanks
* 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
---
## Thanks
* 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.
---
## Session Info
```{r sessionInfo}
sessionInfo()
```