-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtutorial.Rmd
400 lines (312 loc) · 13.9 KB
/
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
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
---
title: "Interactive Plotting with Plotly in R"
author: "Steve Kerr & Julian Kath"
institute: "Hertie School"
date: "`r Sys.Date()`"
output:
html_document:
toc: TRUE
df_print: paged
number_sections: FALSE
highlight: tango
theme: lumen
toc_depth: 3
toc_float: true
css: magic/custom.css
self_contained: false
includes:
after_body: magic/footer.html
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, message = FALSE, warning = FALSE)
```
***
Welcome to **plotly**! plotly is an R package for creating **interactive** and **dynamic** **web-based** graphics.
What we will cover:
* installing plotly
* ggplot vs. plotly syntax
* fundamental plots
* ggplotly
* pro tips
* Q&A
# Install `r emo::ji("woman_technologist")``r emo::ji("man_technologist")`
```{r install, eval=TRUE, message=FALSE, warning=FALSE, results='hide'}
# Download from CRAN
if (!require("plotly")) install.packages("plotly")
# load plotly
library(plotly)
```
# ggplot2 vs. plotly
Last week we learned about ggplot2's grammar of graphics. Today we'll examine how plotly's syntax differs from that of ggplot2.
## ggplot2
Let's quickly recap ggplot2's grammar of graphics. In most cases you start with `ggplot()`, supply a data set and aesthetic mapping (with `aes()`). You then add on layers (e.g., `geom_point()` or `geom_histogram()`), scales (e.g., `scale_colour_brewer()`), faceting specifications (e.g., `facet_wrap()`) and coordinate systems (e.g., `coord_flip()`).
[(more info >>>)](https://ggplot2.tidyverse.org/)
Here's a template for building graphics with ggplot2:
```
ggplot(data = <DATA>) +
<GEOM_FUNCTION>(
mapping = aes(<MAPPINGS>),
stat = <STAT>,
position = <POSITION>
) +
<COORDINATE_FUNCTION> +
<FACET_FUNCTION>
```
Here's an example of ggplot2 in action:
```{r ggplot2, fig.align='center'}
library(ggplot2)
ggplot(iris) + # Add data
geom_point(
mapping = aes(x = Petal.Length, y = Sepal.Length, color = Species)) + # Add mappings
labs(title = "Petal vs. Sepal Lengths", # Add title & labels
x = "Petal Length",
y = "Sepal Length",
color = "Species") + # Add legend title
theme_minimal() # Add theme
```
## plotly
The grammar of plotly is similar to that of ggplot2. Like ggplot2, you start with a base and add layers.
### Trace
In plotly, the base is referred to as a "trace." A trace defines a mapping from data and visuals. Every trace has a type (e.g., histogram, pie, scatter, etc) and the trace type determines what other attributes (i.e., visual and/or interactive properties, like x, hoverinfo, name) are available to control the trace mapping.
To add a layer in the graph, such as fitting a linear regression line, we use `add_trace()`. There is also a family of `add_*()` functions (e.g., `add_histogram()`, `add_lines()`, etc) that define how to render data into geometric objects. [(more info >>>)](https://jtr13.github.io/spring19/community_contribution_group17.html)
List of `add_*()` functions:
* `add_histograms()`
* `add_bars()`
* `add_boxplot()`
* `add_contour()`
* `add_lines()`
* `add_heatmap()`
* `add_scattergeo()`
* `add_pie()`
* and many more...
### Layout
The `layout()` function adds and modifies parts of the plotly graphic. This includes modifying the plot title, legend, margins, size, font, background color, colorscale, and hoverlabels among other features.
Here's how you would create the plot from above using plotly:
```{r plotly, fig.align='center'}
library(plotly)
iris %>% # Add data
# NOTE: You will need to use `~` to map a variable of the data set to an aesthetic parameter
plot_ly(x = ~Petal.Length, y = ~Sepal.Length, split = ~Species, # Add mappings
type = 'scatter') %>% # Specify trace type
layout(title = 'Petal vs. Sepal Length', # Add title & labels
xaxis = list(title = 'Petal Length'),
yaxis = list(title = 'Sepal Length'),
legend = list(title = list(text = 'Species')), # Add legend title
plot_bgcolor = 'white') # Modify background color
```
Notice that even while the plots look quite similar, the syntax we use to create them can be quite different.
To underscore this point, the table below shows the differences in ggplot2 and plotly grammar:
| Element | ggplot2 | plotly |
|--- |--- |--- |
| Data & Aesthetics | `ggplot(data = mpg, aes(x = displ, y = hwy, color = drv))` | `plot_ly(data = mpg, x = ~displ, y = ~hwy, color = ~drv)` |
| Geometries | `+ geom_point()` | `%>% add_markers()` |
| Facets | `+ facet_grid(vars(drv), ncol = 1)` | `%>% subplot(fig1, fig2)` or use `ggplotly()` |
| Labels | `+ labs(x = "Height", y = "Weight", title = "Look at my plot")` | ` %>% layout(title = 'Look at my plot', xaxis = list(title = 'Height'), yaxis = list(title = 'Weight')` |
### schema( )
The standard documentation retrieved via `?plot_ly()` and specific traces is oftentimes not particularly helpful. You can access a more elaborate documentation via the `schema()` command. Not only is there much more information, the hierarchical list structure also gives a better overview of the underlying logic and syntax of plotly.
```{r schema}
# Check it out!
schema()
```
# Fundamental Plots
While the possibilities with plotly are almost endless, here are several fundamental plots that will likely be useful.
```{r fundamentals}
# scatterplot
plot_ly(mpg, x = ~displ, y = ~hwy, color = ~class) %>%
add_markers()
# line plot
plot_ly(economics, x = ~date, y = ~uempmed) %>%
add_paths()
# ribbons
plot_ly(economics, x = ~date) %>%
add_ribbons(ymin = ~pce - 1e3, ymax = ~pce + 1e3)
# use `add_sf()` or `add_polygons()` to create geo-spatial maps
# http://blog.cpsievert.me/2018/03/30/visualizing-geo-spatial-data-with-sf-and-plotly/
if (requireNamespace("sf", quietly = TRUE)) {
nc <- sf::st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE)
plot_ly() %>% add_sf(data = nc)
}
# univariate summary statistics
# boxplot
plot_ly(mtcars, x = ~factor(vs), y = ~mpg) %>%
add_boxplot()
# violin
plot_ly(mtcars, x = ~factor(vs), y = ~mpg) %>%
add_trace(type = "violin")
# histogram
# `add_histogram()` does binning for you...
diamonds %>%
plot_ly(x = ~cut) %>%
add_histogram()
# bar chart
# ...you can also 'pre-compute' bar heights in R
diamonds %>%
dplyr::count(cut) %>%
plot_ly(x = ~cut, y = ~n) %>%
add_bars()
# 2D histogram
library(MASS)
plot_ly(geyser, x = ~waiting, y = ~duration) %>%
add_histogram2d()
# 2D histogram contour
plot_ly(geyser, x = ~waiting, y = ~duration) %>%
add_histogram2dcontour()
# heatmap
# (i.e., bin counts must be pre-specified)
den <- kde2d(geyser$waiting, geyser$duration)
plot_ly(x = den$x, y = den$y, z = den$z) %>%
add_heatmap()
# heatmap contour
den <- kde2d(geyser$waiting, geyser$duration)
plot_ly(x = den$x, y = den$y, z = den$z) %>%
add_contour()
# `add_table()` makes it easy to map a data frame to the table trace type
plot_ly(economics) %>%
add_table()
# pie chart
ds <- data.frame(labels = c("C", "B", "A"), values = c(10, 40, 60))
plot_ly(ds, labels = ~labels, values = ~values) %>%
add_pie() %>%
layout(title = "Basic Pie Chart using Plotly")
# radial pie chart
data(wind)
plot_ly(wind, r = ~r, t = ~t) %>%
add_area(color = ~nms) %>%
layout(radialaxis = list(ticksuffix = "%"), orientation = 270)
# 3D surface plot
# Not the most useful trace type but it's still very interesting!
plot_ly(z = ~volcano) %>%
add_surface()
```
# ggplotly
The `ggplotly()` function has the ability to translate ggplot2 to plotly. This functionality can be really helpful for quickly adding interactivity to your existing ggplot2 workflow. Moreover, even if you know plotly well, you can still leverage ggplot2’s consistent and expressive interface for exploring statistical summaries across groups. [(more info >>>)](https://plotly-r.com/overview.html#intro-ggplotly)
Take advantage of ggplotly by plotting a regular ggplot2 graphic and then applying the `ggplotly()` function. Here's an example using the `iris` data set from earlier.
```{r ggplotly, message=FALSE, warning=FALSE, fig.align='center'}
library(ggplot2)
library(plotly)
g <- ggplot(iris) + # Add data
geom_point(
mapping = aes(x = Petal.Length, y = Sepal.Length, color = Species), # Add mappings
position = position_jitter()) + # Modify position
labs(title = "Petal vs. Sepal Lengths",
x = "Petal Length", # Add title & labels
y = "Sepal Length",
color = "Species") + # Add legend title
theme_minimal() + # Add theme
theme(legend.position = "right") # Adjust legend position
ggplotly(g)
```
# Pro Tips
## Hover Info
Editing the tooltip that shows up when hovering over plotly graphics can be a pain. At the same time, this is typically the first thing you would want to do when creating a plot since the hoverinfo is the most basic interactive feature.
The key parameters for customizing the tooltip are:
• `hoverinfo`: Using this in combination with the `text`-argument the most straight-forward way to do this.
• `hovertemplate`: takes a particular formula and overwrites whatever is in the hoverinfo. This might be what you are looking for when you also want your formats to correspond with the x-axis format.
• `text`: will add text to the tooltip box. If you wish to delete the displayed hoverinfo, specify `hoverinfo = "text"`. You can add basically everything here, just pay attention to where to put the `~` operator!
There are a number of ways to go about this:
```{r hoverinfo code, message=FALSE}
hover_map <- function(text,
hoverinfo,
hovertemplate,
title) { # Defining function for subsequent mapping
plot_ly(mtcars,
x = ~mpg,
y = ~hp,
color = ~as.factor(gear),
text = text,
hoverinfo = hoverinfo, # Passing hoverinfo here!
hovertemplate = hovertemplate, # Passing hovertemplate!
hoverlabel = list( # This is simply to demonstrate how to change the layout of the tooltip.
bgcolor = "#348597", # Background colour of the tooltip.
bordercolor = "transparent", # Contour of the tooltip box
font = list( # Specifying the font type, size and color
family = "Times New Roman",
size = 15,
color = "white"
)
) # Notice how neither type nor trace are defined. Plotly interprets the passed data as a scatter
) %>%
layout(
annotations = # Setting the subplot labels, a workaround as individual subplot titles are not supported :(
list(
x = 0.3,
y = 1.075,
text = title,
showarrow = F,
xref = 'paper',
yref = 'paper')
) %>%
hide_legend()
}
hover_list <- list( # Creating a list to pass to pmap(). We will show 4 options
text = list( # Parameters passed to text in the plot_ly call above
paste0("Just a normal vector </br>", row.names(mtcars)),
~paste0(
"</br> MPG: ", mpg,
"</br> HP: ", hp,
"</br> Cyl: ", cyl,
"</br>", emo::ji("car")
),
NULL,
~qsec
),
hoverinfo = list( # Parameters passed to hoverinfo
NULL,
"text",
NULL,
"text"
),
hovertemplate = list( # Parameters passed to hovertemplate
NULL,
NULL,
"The car has %{y:$} HP </br>
and it has %{x:.1e} MPG.<extra> This is outside the box!</extra>",
NULL
),
title = list( # Subplot titles
"Passing a vector to hovertext",
"Custom paste0 formula tooltip",
"Using hovertemplate",
"Passing a single variable to hovertext"
)
)
plots <- purrr::pmap(hover_list, hover_map)
hover_plot <- subplot(plots, nrows = 2, shareX = T, shareY = T)
```
```{r hoverinfo plot, echo=FALSE}
hover_plot
```
If you want to simply include variables that are already in the plot (e.g. mapped x, y variables) to the hover text, we would recommend using the `hovertemplate` as it brings you more flexibility and is way easier for customizing the format of the hover text. If there are more variables involved, set `hoverinfo = "text"` and `text = ~paste("whatever", variable, "you wish, using </br> for line breaks!")`.
**Pay attention:** The tooltip is adjusted differently when using `ggplotly()`. By default all values mapped to `aes()` will be included. to restrict this include `tooltip = "text"` in the ggplotly call. You can also pass a vector to `tooltip`.
## Linked Plots
As briefly touched upon in the video, the `crosstalk` library is essential for creating linked plots.
To do so, initiate a `SharedData` object, build the two plots you would like to link and use the `subplot()` command to connect them. You can specify the highlighting type in the `highlight()` command's on-parameter.
```{r linked plots, message=FALSE}
library(crosstalk)
shared_data <- SharedData$new(mtcars) # Creating the shared data object
p1 <- shared_data %>% # Building the first plot
plot_ly(
x = ~mpg,
y = ~hp
)
p2 <- shared_data %>% # Building the second plot
plot_ly(
x = ~qsec,
y = ~wt
)
subplot(p1, p2) %>% # Connecting them with subplot
highlight(on = "plotly_selected") %>% # Highlighting with box selection
hide_legend()
```
# Q&A
```{r Q&A, fig.align='center', echo=FALSE, out.width = "90%"}
knitr::include_graphics("pics/questions.png")
```
# Sources
This tutorial drew from the following sources:
* [Interactive web-based data visualization with R, plotly, and shiny](https://plotly-r.com)
* [R for Data Science, Ch.3 Data Visualisation](https://r4ds.had.co.nz/data-visualisation.html)
* [A Comparison of plot_ly and ggplotly for Interactive Graphs in R](https://jtr13.github.io/spring19/community_contribution_group17.html)
* [Package 'plotly'](https://cran.r-project.org/web/packages/plotly/plotly.pdf)
* [Introduction to ggplot2](https://ggplot2.tidyverse.org/)
We also used [examples](https://blog.methodsconsultants.com/posts/introduction-to-interactive-graphics-in-r-with-plotly/) from Michael Battaglia's blog post entitled, "Introduction to Interactive Graphics in R with plotly."