-
Notifications
You must be signed in to change notification settings - Fork 633
/
Copy pathintro.Rmd
208 lines (152 loc) · 7.17 KB
/
intro.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
---
title: "An overview of plotly's R API"
author: "Carson Sievert"
output: rmarkdown::html_vignette
vignette: >
%\VignetteEngine{knitr::rmarkdown}
%\VignetteIndexEntry{Plotly DSL}
---
```{r, echo = FALSE}
knitr::opts_chunk$set(
message = FALSE,
warning = FALSE,
fig.width = 7,
fig.height = 3
)
```
To create a plotly visualization, start with `plot_ly()`.
```{r}
library(plotly)
plot_ly(economics, x = date, y = unemploy / pop)
```
A plotly visualization is composed of one (or more) trace(s), and every trace has a `type` (the default type is 'scatter'). The arguments/properties that a trace will respect ([documented here](https://plot.ly/r/reference)) depend on it's type. A scatter trace respects `mode`, which can be any combination of "lines", "markers", "text" joined with a "+":
```{r}
library(plotly)
plot_ly(economics, x = date, y = unemploy / pop,
type = "scatter", mode = "markers+lines")
```
You can manually add a trace to an existing plot with `add_trace()`. In that case, you'll want to either `name` your traces, or hide the legend by setting `showlegend = FALSE`
```{r}
m <- loess(unemploy / pop ~ as.numeric(date), data = economics)
p <- plot_ly(economics, x = date, y = unemploy / pop, name = "raw")
add_trace(p, x = date, y = fitted(m), name = "loess")
```
__plotly__ was designed with a [pure, predictable, and pipeable interface](https://dl.dropboxusercontent.com/u/41902/pipe-dsls.pdf) in mind, so you can also use the `%>%` operator to create a visualization pipeline:
```{r}
economics %>%
plot_ly(x = date, y = unemploy / pop) %>%
add_trace(x = date, y = fitted(m)) %>%
layout(showlegend = F)
```
Furthermore, `plot_ly()`, `add_trace()`, and `layout()`, all accept a data frame as their first argument and output a data frame. As a result, we can inter-weave data manipulations and visual mappings in a single pipeline.
```{r}
economics %>%
transform(rate = unemploy / pop) %>%
plot_ly(x = date, y = rate) %>%
subset(rate == max(rate)) %>%
layout(
showlegend = F,
annotations = list(x = date, y = rate, text = "Peak", showarrow = T)
)
```
Although these functions output special "plotly data frames", `plot_ly()` doesn't require a data frame for input. This makes chart types that accept a `z` argument especially easy to use if you have a numeric matrix:
```{r, eval = FALSE}
s <- plot_ly(z = volcano, type = "surface")
```
If you have [a free plotly account](https://plot.ly/r/getting-started/), `plotly_POST()` makes it easy to host/share any plotly figure.
```{r, eval = FALSE}
plotly_POST(s)
```
```{r, results = 'asis', echo = FALSE}
cat(plotly:::plotly_iframe("https://plot.ly/~agvd/1794/", 600, 600))
```
## Special arguments
The __plotly__ function arguments used thus far are documented in [the figure reference](https://plot.ly/r/reference), but there are a handful of additional arguments not described in the reference that make common visualizations a bit easier. These arguments are very much inspired by the semantics of ggplot2's `qplot()` in the sense that a scales are automatically applied these variables.
### The color argument
#### Qualitative color mappings
If a ordinal variable (aka a non-ordered factor variable) is assigned to color, then a qualitative color palette is used by default.
```{r}
plot_ly(iris, x = Petal.Length, y = Petal.Width,
color = Species, mode = "markers")
```
If you want to change the default palette, it's recommended that you provide a <http://colorbrewer2.org> qualitative pallette name (e.g., "Set1" or "Accent") to the colors argument.
```{r}
plot_ly(iris, x = Petal.Length, y = Petal.Width,
color = Species, colors = "Set1", mode = "markers")
```
In this case, the palette consists of 9 colors and the default behavior is to pick colors that are furthest apart ("#E41A1C", "#FF7F00", and "#999999").
```{r}
cols <- RColorBrewer::brewer.pal(9, "Set1")
scales::show_col(cols)
```
If you'd like more control over the mapping, you can provide a vector of colors (of appropriate length).
```{r}
cols <- RColorBrewer::brewer.pal(nlevels(iris$Species), "Set1")
plot_ly(iris, x = Petal.Length, y = Petal.Width,
color = Species, colors = cols, mode = "markers")
```
#### Sequential color mappings
If either a numeric or an ordered factor is mapped to color, `plot_ly()` applies a sequential color scale by default.
```{r}
plot_ly(iris, x = Petal.Length, y = Petal.Width,
color = as.ordered(Species), mode = "markers")
```
In the case of continuous numeric variables, `plot_ly()` performs a linear mapping between the data and an interpolated color pallette.
```{r}
plot_ly(iris, x = Petal.Length, y = Petal.Width,
color = Sepal.Length, mode = "markers")
```
The colors argument takes arbitrary color codes of arbitrary length. Here is how we could use it to replicate the default mapping in ggplot2.
```{r}
plot_ly(iris, x = Petal.Length, y = Petal.Width,
color = Sepal.Length, colors = c("#132B43", "#56B1F7"),
mode = "markers")
```
#### Diverging color mappings
To obtain a diverging color mapping, just provide a diverging palette to the colors argument.
```{r}
plot_ly(iris, x = Petal.Length, y = Petal.Width,
color = Sepal.Length, colors = "PuOr", mode = "markers")
```
### The symbol argument
To encode values using symbols, use the symbol argument.
```{r}
plot_ly(iris, x = Petal.Length, y = Petal.Width,
symbol = Species, mode = "markers")
```
To change the default symbols used, use the symbols argument. All the valid symbol types are listed [here](https://plot.ly/r/reference/#marker).
```{r}
plot_ly(iris, x = Petal.Length, y = Petal.Width, mode = "markers",
symbol = Species, symbols = c("cross", "square", "triangle-down"))
```
### The group argument and `subplot()`
Using the group argument splits the data into different plotly "traces".
```{r}
plot_ly(iris, x = Petal.Length, y = Petal.Width,
group = Species, mode = "markers")
```
Although we haven't specified a coloring scheme, plotly will employ one on it's own default scheme. The group argument is quite powerful when used in conjunction with `subplot()` in order to anchor traces onto different axes.
```{r}
iris$id <- as.integer(iris$Species)
p <- plot_ly(iris, x = Petal.Length, y = Petal.Width, group = Species,
xaxis = paste0("x", id), mode = "markers")
subplot(p)
```
Since `subplot()` does not assume x/y axes are on a common scale, it does not impose any restrictions on the range by default. However, you can change this by pre-specifying the range of the [axis objects](https://plot.ly/r/reference/#xaxis) via the `layout()` function.
```{r}
p2 <- layout(
p,
xaxis = list(range = range(Petal.Length) + c(-0.1, 0.1)),
yaxis = list(range = range(Petal.Width) + c(-0.1, 0.1))
)
subplot(p2)
```
Part of the magic of `subplot()` is that it generates axis objects with appropriate anchor and domain properties. After generating a subplot, you can always reference these axis objects to customize each plot.
```{r}
layout(
subplot(p2),
yaxis2 = list(title = ""),
yaxis3 = list(title = "")
)
```
[See here](https://plot.ly/r/map-subplots-and-small-multiples/) for another example of using the group argument to make small multiples (with maps!).