-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy path18-Programming-with-ggplot2.Rmd
328 lines (257 loc) · 8.31 KB
/
18-Programming-with-ggplot2.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
# (PART\*) Advanced Topics {-}
# Programming with ggplot2
**Learning objectives:**
- Programming single and multiple components
- Use components, annotation, and additional arguments in a plot
- Functional programming
---
```{r message=FALSE, warning=FALSE, include=FALSE, paged.print=FALSE}
library(tidyverse)
```
## Why program with {ggplot2}? {-}
To reduce duplicated code, build up repeated components
Can also generalize code to allow for flexibility
### Plot components are objects! {-}
One example of a component of a plot is this one below:
```{r}
bestfit <- geom_smooth(
method = "lm",
se = FALSE,
colour = alpha("steelblue", 0.5),
linewidth = 2)
class(bestfit)
```
## Adding the object we created to a plot {-}
Place component in grammar of graphics syntax to use as a plot layer
```{r}
ggplot(mpg, aes(cty, hwy)) +
geom_point() +
bestfit
```
## Creating a function {-}
Another way is to build a layer via a function:
```{r}
geom_lm <- function(formula = y ~ x, colour = alpha("steelblue", 0.5),
linewidth = 2, ...) {
geom_smooth(formula = formula, se = FALSE, method = "lm", colour = colour,
linewidth = linewidth, ...)
}
```
Use the layer in the plot:
```{r}
ggplot(mpg, aes(displ, 1 / hwy)) +
geom_point() +
geom_lm(y ~ poly(x, 2), linewidth = 1, colour = "red")
```
## `...` gives functions flexibility {-}
The `...` parameter lets a function accept additional arbitrary arguments
e.g. `na.rm` (doesn't make a difference in this case, but the function accepts it!)
```{r}
ggplot(mpg, aes(displ, 1 / hwy)) +
geom_point() +
geom_lm(y ~ poly(x, 2), linewidth = 1, colour = "red", na.rm = T)
```
## Exercises {-}
1. Create an object that represents a pink histogram with 100 bins.
```{r}
pinkhist <- geom_histogram(fill = "pink", bins = 100)
ggplot(diamonds, aes(x = price)) +
pinkhist +
labs(y = "Frequency",
x = "Price")
```
2. Create an object that represents a fill scale with the Blues ColorBrewer palette.
```{r}
blues_fill_scale <- scale_fill_brewer(palette = "Blues")
ggplot(data = diamonds, aes(x = cut, y = price, fill = cut))+
geom_boxplot()+
theme_minimal()+
blues_fill_scale
```
3. Read the source code for theme_grey(). What are its arguments? How does it work?
```{r}
theme_grey
# It creates a theme object called t
# uses %+replace% to replace the existing theme with t
# ggplot_global$theme_all_null %+replace% t
# ggplot_global$theme_all_null doesn't exist globally, so must refer to the current plot that you're adding theme_grey to.
```
4. Create scale_colour_wesanderson(). It should have a parameter to pick the palette from the wesanderson package, and create either a continuous or discrete scale.
```{r}
library(wesanderson)
scale_colour_wesanderson <- function(palette, type = "discrete", ...){
scale_color_manual(values = wes_palette(name = palette, type = type, ...), ...)
}
ggplot(diamonds, aes(x = carat, y = price, color = cut))+
geom_point()+
scale_colour_wesanderson(palette = "Cavalcanti1")+
theme_minimal()
```
## A ggplot object is a list!
And therefore, we can add more than one component as a list.
```{r}
geom_mean <- function() {
list(
stat_summary(fun = "mean", geom = "bar", fill = "grey70"),
stat_summary(fun.data = "mean_cl_normal", geom = "errorbar", width = 0.4)
)
}
```
```{r message=FALSE, warning=FALSE, paged.print=FALSE}
ggplot(mpg, aes(class, cty)) + geom_mean()
```
## Components of a plot {-}
- data.frame
- aes()
- Scales
- Coords systems
- Theme components
## We can add any of these to a plot and override existing {-}
For datasets, use `%+%`
```{r}
dataset1 <- data.frame(id = rep(letters[1:3], each = 100),
Value = c(rnorm(100, mean = 1),
rnorm(100, mean = 2),
rnorm(100, mean = 3)))
dataset2 <- data.frame(id = rep(letters[1:3], each = 100),
Value = c(rpois(100, lambda = 1),
rpois(100, lambda = 2),
rpois(100, lambda = 3)))
p1 <- ggplot(dataset1, aes(x = Value, col = id))+
geom_density()+
theme_minimal()
p1
p2 <- p1 %+% dataset2
p2
```
## What if the dataset doesn't have the same variables? {-}
```{r error = T}
dataset3 <- data.frame(id = rep(letters[1:3], each = 100),
test = c(rpois(100, lambda = 4),
rpois(100, lambda = 5),
rpois(100, lambda = 6)))
# Try to add a new dataset, but it doesn't work because the code for p1 is expecting a "Value" column and that column doesn't exist in dataset3.
p1 %+%
dataset3
```
Why doesn't this work?
```{r}
# Let's override the y aesthetic...
new_aes <- aes(y = test)
p3 <- p1 +
new_aes %+%
dataset3 #
p3
```
## Annotations {-}
Make sure to set `inherit.aes = FALSE` and `show.legend = FALSE`
> "A quick and dirty way to get map data (from the maps package) on to your plot."
```{r}
borders <- function(database = "world", regions = ".", fill = NA,
colour = "grey50", ...) {
df <- map_data(database, regions)
geom_polygon(
aes_(~long, ~lat, group = ~group),
data = df, fill = fill, colour = colour, ...,
inherit.aes = FALSE, show.legend = FALSE
)
}
```
```{r message=FALSE, warning=FALSE, paged.print=FALSE}
library(maps)
data(us.cities)
capitals <- subset(us.cities, capital == 2)
ggplot(capitals, aes(long, lat)) +
borders("world", xlim = c(-130, -60), ylim = c(20, 50)) +
geom_point(aes(linewidth = pop)) +
scale_size_area() +
coord_quickmap()
```
## Additional arguments {-}
"If you want to pass additional arguments to the components in your function, ... is no good: there’s no way to direct different arguments to different components. Instead, you’ll need to think about how you want your function to work, balancing the benefits of having one function that does it all vs. the cost of having a complex function that’s harder to understand."
modifyList()
do.call()
```{r}
geom_mean <- function(..., bar.params = list(), errorbar.params = list()) {
params <- list(...)
bar.params <- modifyList(params, bar.params)
errorbar.params <- modifyList(params, errorbar.params)
bar <- do.call("stat_summary", modifyList(
list(fun = "mean", geom = "bar", fill = "grey70"),
bar.params)
)
errorbar <- do.call("stat_summary", modifyList(
list(fun.data = "mean_cl_normal", geom = "errorbar", width = 0.4),
errorbar.params)
)
list(bar, errorbar)
}
```
And here is the result:
```{r}
ggplot(mpg, aes(class, cty)) +
geom_mean(
colour = "steelblue",
errorbar.params = list(width = 0.5, size = 1)
)
```
## Making the complete plot--very limited flexibility {-}
```{r}
piechart <- function(data, mapping) {
ggplot(data, mapping) +
geom_bar(width = 1) +
coord_polar(theta = "y") +
xlab(NULL) +
ylab(NULL)
}
piechart(mpg, aes(factor(1), fill = class))
```
## What if we want to pass in different variables? {-}
- Instead of writing out the entire `aes()`, the user can just pass in the variable names
- But there's a catch!
This doesn't work:
```{r}
my_function <- function(x_var) {
aes(x = x_var)
}
my_function(abc)
#> Aesthetic mapping:
#> * `x` -> `x_var`
```
We can "embrace" the argument to tell ggplot2 to "look inside" the argument and use its value, not its expression
```{r}
my_function <- function(x_var) {
aes(x = {{x_var}})
}
my_function(abc)
#> Aesthetic mapping:
#> * `x` -> `abc`
```
New version of the piechart function:
```{r}
piechart <- function(data, var) {
ggplot(data, aes(factor(1), fill = {{ var }})) +
geom_bar(width = 1) +
coord_polar(theta = "y") +
xlab(NULL) +
ylab(NULL)
}
mpg |> piechart(class)
```
## References {-}
- [extending ggplot2](https://ggplot2.tidyverse.org/articles/extending-ggplot2.html)
- [functions](https://adv-r.hadley.nz/functions.html)
- [expressions](http://adv-r.had.co.nz/Expressions.html)
- [functional programming](http://adv-r.had.co.nz/Functional-programming.html)
- [advanced R - functionals](https://adv-r.hadley.nz/fp.html)
---
## Meeting Videos
### Cohort 1
`r knitr::include_url("https://www.youtube.com/embed/jf-Qn4iFqHY")`
<details>
<summary> Meeting chat log </summary>
```
00:41:31 Priyanka Gagneja: There’s a lot of disturbance :(
01:00:48 Priyanka Gagneja: https://plotly.com/ggplot2/setting-graph-size/
```
</details>