-
Notifications
You must be signed in to change notification settings - Fork 109
/
GoogleVis_tutorial.Rmd
210 lines (154 loc) · 10.7 KB
/
GoogleVis_tutorial.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
# GoogleVis
Junyang Jiang and Alex Wan
## Overview
This section covers how to make charts with googleVis.
Google Charts Tools is a powerful online tool that enables users to create attractive graphical charts and embed them in Web pages with JavaScript. And the googleVis package can help R users take fully advantage of Google charts tools, which provides an interface between R and the Google charts tools and allows users to create interactive charts based on R data frames. This package (Version 0.6.4) provides interfaces to Motion Charts, Annotated Time, Lines, Maps, Geo Maps, Geo Charts, Intensity Maps, Tables, Gauges, Tree Maps, further Line, Bar, Bubble, Column, Area, Stepped Area, Combo, Scatter, Candlestick, Pie, Sankey, Annotation, Histogram, Timeline, Calendar and Org Charts.
## Example: Line chart
Let’s use GDP dataset from `wbstats` to have a look at how googleVis draws line chart.
Here’s the code for preparing dataset:
```{r}
library(wbstats)
suppressMessages(library(googleVis))
op <- options(gvis.plot.tag='chart') # set googleVis plot option to display chart in RMarkdown
dat <- wb(indicator='NY.GDP.PCAP.KD', country=c('MX','CA','US','CH','IN','JP'), start=1980, end=2018)[c("country","value","date")]
gdp <- as.data.frame.matrix(xtabs(value ~ date + country, data=dat))
gdp <- cbind(rownames(gdp),gdp)
colnames(gdp)[1] <- "date"
head(gdp)
```
Then use the `gvisLineChart` method to initialize the chart and then the `plot()` method to render it:
```{r LineExample, results='asis', tidy=FALSE}
Line <- gvisLineChart(gdp, xvar = "date", yvar = c("Mexico", "United States"))
plot(Line)
```
where `xvar` is name of the character column which contains the category labels for the x-axes and `yvar` is a vector of column names of the numerical variables to be plotted. GoogleVis allows users to pass list of configuration options by using a named list `options`. The parameters have to map those
of [the Google documentation](https://google-developers.appspot.com/chart/interactive/docs/gallery/linechart#configuration-options). Note that you need to use the R syntax and wrap configuration options into a character. For more details see the Google API documentation and the googleVis Reference Manual.
In the following code, we create a line chart with two axis:
```{r LineExample2, results='asis', tidy=FALSE}
Line <- gvisLineChart(gdp, xvar = "date", yvar = c("Mexico", "United States"),
options=list(
series="[{targetAxisIndex: 0},
{targetAxisIndex:1}]",
vAxes="[{title:'Mexico'}, {title:'United States'}]"
))
plot(Line)
```
To smooth the lines, you can curve the Lines by setting the `curveType` option to `"function"`:
```{r LineExample3, results='asis', tidy=FALSE}
Line <- gvisLineChart(gdp, xvar = "date", yvar = c("Mexico", "United States"),
options=list(
series="[{targetAxisIndex: 0},
{targetAxisIndex:1}]",
vAxes="[{title:'Mexico'}, {title:'United States'}]",
curveType='function'
))
plot(Line)
```
Compared to `ggplot2`, googleVis provides more interactive features. For example, you can target a single element using [Crosshairs](https://google-developers.appspot.com/chart/interactive/docs/crosshairs):
```{r LineExample4, results='asis', tidy=FALSE}
Line <- gvisLineChart(gdp, xvar = "date", yvar = c("Mexico", "United States"),
options=list(
series="[{targetAxisIndex: 0},
{targetAxisIndex:1}]",
vAxes="[{title:'Mexico'}, {title:'United States'}]",
crosshair="{ trigger: 'both' }"
))
plot(Line)
```
This method are available for other charts including scatter charts, line charts, area charts, and combo charts. If the lines are too intensive or you would like to find detailed information of a line, you should use `explorer` function. This option allows users to pan and zoom Google charts. Setting `dragToZoom` allows users to zoom in and out when scrolling and `rightClickToReset` is for returning it to the original pan and zoom level clicking on the chart. You can also try other options like `dragToPan` and `explorer.maxZoomIn`.
```{r LineExample5, results='asis', tidy=FALSE}
Line <- gvisLineChart(gdp,
options=list(
explorer="{actions: ['dragToZoom', 'rightClickToReset']}"
))
plot(Line)
```
## Example: Geo Chart
Geochart is far more interesting chart for showing GDP for different countries.
> A geochart is a map of a country, a continent, or a region with areas identified in one of three ways:
> * The region mode colors whole regions, such as countries, provinces, or states.
> * The markers mode uses circles to designate regions that are scaled according to a value that you specify.
> * The text mode labels the regions with identifiers (e.g., "Russia" or "Asia").
In googleVis, creating geochart is simple. For regions mode format, you can call `gvisGeoChart` function and pass data containing region location and region color. Region location is a string of a country name (for example, "England") or region code name (for example, "US") or an area code. Region color is a numeric column used to assign a color to this region (for example, gdp value in our example). Note that [markers mode format](https://developers.google.com/chart/interactive/docs/gallery/geochart#markers-mode-format) and [text mode](https://developers.google.com/chart/interactive/docs/gallery/geochart#text-mode-format) format have slightly different formats.
```{r GeoExample, results='asis', tidy=FALSE}
dat <- wb(indicator='NY.GDP.PCAP.KD', start=2018, end=2018)
Geo <- gvisGeoChart(dat, "iso2c", "value")
print(Geo)
```
Like other chart, you can customize the colors of GeoCharts for background color, chart fill color, chart border color, etc. Please check [correct format](https://developers.google.com/chart/interactive/docs/gallery/geochart#coloring-your-chart).
```{r GeoExample2, results='asis', tidy=FALSE}
Geo <- gvisGeoChart(dat, "iso2c", "value",
options=list(
colorAxis="{colors:['yellow', 'orange', 'red', 'purple']}",
backgroundColor="lightblue")
)
print(Geo)
```
One important feature of googleVis is `ChartEditor Class` which is used to open an in-page dialog box that enables a user to customize a visualization on the fly. In this method, you can customize color, region, chart type and so on directly. And this class works for most Google Charts.
Try click the "Edit me!" button in the following chart and see what happens.
```{r GeoExample3, results='asis', tidy=FALSE}
Geo <- gvisGeoChart(dat, "country", "value",
options=list(
gvis.editor="Edit me!")
)
plot(Geo)
```
## Example: Sankey chart
GoogleVis can draw Sankey chart as well.
> A sankey diagram is a visualization used to depict a flow from one set of values to another. The things being connected are called nodes and the connections are called links. Sankeys are best used when you want to show a many-to-many mapping between two domains (e.g., universities and majors) or multiple paths through a set of stages (for instance, Google Analytics uses sankeys to show how traffic flows from pages to other pages on your web site).
For A, b
```{r SankeyExample, results='asis', tidy=FALSE}
# From Google Charts Guide
data <- data.frame(From=c(rep("A",3), rep("B", 3)),
To=c(rep(c("X", "Y", "Z"),2)),
Weight=c(5,7,6,2,9,4))
Sankey <- gvisSankey(data, from="From", to="To", weight="Weight")
plot(Sankey)
```
You can also create a Sankey chart with multiple levels of connections.
```{r SankeyExample2, results='asis', tidy=FALSE}
# From googleVis Examples on CRAN
data <- data.frame(From=c(rep("A",3), rep("B", 3), rep("X",2), "Y", rep("Z",3), "W"),
To=c(rep(c("X", "Y", "Z"),2), c("M", "N"), "M", c("M", "N", "W"), "M"),
Weight=c(5,7,6,2,9,4,2,3,10,2,8,3,4))
Sankey <- gvisSankey(data, from="From", to="To", weight="Weight")
plot(Sankey)
```
You can set custom colors for nodes and links using `sankey.node` and `sankey.node`. Both nodes and links can be given custom color palettes using their colors options. You can also set a coloring mode for the links between nodes using the `colorMode` option.
```{r SankeyExample3, results='asis', tidy=FALSE}
# From googleVis Examples on CRAN
data <- data.frame(From=c(rep("A",3), rep("B", 3), rep("X",2), "Y", rep("Z",3), "W"),
To=c(rep(c("X", "Y", "Z"),2), c("M", "N"), "M", c("M", "N", "W"), "M"),
Weight=c(5,7,6,2,9,4,2,3,10,2,8,3,4))
Sankey <- gvisSankey(data, from="From", to="To", weight="Weight",
options=list(
sankey="{link: {color: { fill: '#d799ae' } },
node: {color: { fill: '#a61d4c' },
label: { color: '#871b47'} }}"))
plot(Sankey)
```
```{r resetOptions}
## Set options back to original options
options(op)
```
There are more interesting charts designed to address your data visualization needs we do not cover in this tutorial. Please see [Chart Gallery](https://google-developers.appspot.com/chart/interactive/docs/gallery) if you like.
## googleVis in RStudio
Writing googleVis in RStudio is easy. Normally after runing `plot` command it will open a standalone browser window and render charts in the web page. Besides, RStudio also supports viewing local web content in [Viewer pane](https://support.rstudio.com/hc/en-us/articles/202133558-Extending-RStudio-with-the-Viewer-Pane). You can also use command
```
plot(object, browser=rstudioapi::viewer)
```
instead of `plot(object)` to view googleVis charts in Viewer window of Rstudio.
To Knit the markdown file to HTML, you should print the chart element only
```{r}
op <- options(gvis.plot.tag='chart')
# or using plot(object, 'chart') when ploting charts
```
and set the chunk option results to ’asis’ with `{r results='asis'}`.
## Reference and Resource
* [googleVis Source Code](https://github.com/mages/googleVis)
* [googleVis CRAN Page](https://github.com/mages/googleVis)
* [googleVis Examples](https://cran.r-project.org/web/packages/googleVis/vignettes/googleVis_examples.html)
* [googleVis Reference Manual](https://cran.r-project.org/web/packages/googleVis/googleVis.pdf)
* [Google Chart Tools Documentation](https://developers.google.com/chart/interactive/docs)
* [Google APIs Terms of Service](https://developers.google.com/terms/)
* [Author's Blog](https://magesblog.com/categories/googlevis/)