-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchapter6_03_ggplot2next.qmd
561 lines (391 loc) · 13.4 KB
/
chapter6_03_ggplot2next.qmd
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
551
552
553
554
555
556
557
558
559
560
561
---
title: Plotting two or more variables with `ggplot2`
format:
revealjs:
logo: monash-stacked-blue-rgb-transparent.png
slide-number: true
show-slide-number: all
controls: true
width: 1280
height: 720
---
```{r setup, include = FALSE}
knitr::opts_chunk$set(#fig.path = "images/chapter6-03/",
fig.align = "center",
fig.width = 6,
fig.height = 3.5,
cache.path = "cache/",
cache = FALSE,
echo = TRUE,
warning = FALSE,
message = FALSE)
library(ozmaps)
library(tidyverse)
oz_sf <- ozmap_data("states")
fig_path <- knitr::opts_chunk$get("fig.path")
```
```{r catalogue-setup, include = FALSE}
set.seed(1)
n1 <- 200
df1 <- tibble(x = runif(n1, 0, 10),
y = 3 * x + rnorm(n1, 0, 10),
z = rnorm(n1, 0, 2),
g1 = sample(letters[1:4], size = n1, replace = TRUE),
g2 = sample(letters[1:4], size = n1, replace = TRUE)) %>%
mutate(g1 = fct_reorder(g1, y, sum))
df2 <- diamonds %>%
sample_n(80)
df3 <- ToothGrowth %>%
mutate(dosef = factor(dose)) %>%
group_by(dosef, supp) %>%
summarise(mlen = factor(mean(len)))
sumdf1 <- df1 %>%
group_by(g1) %>%
summarise(y = sum(y))
sumdf2 <- df1 %>%
group_by(g1, g2) %>%
summarise(y = sum(y))
# generate 5 from colorspace and discard the tails which are too white
reds <- c("#7F000D", "#A9565A", "#CA9496", "#E2CBCB")
yellows <- c("#6A3F00", "#97742F", "#BAA588", "#D4CCC3")
green <- "#006400"
purples <- c("#312271", "#4F4293", "#6D60BB", "#8B80D1", "#A79FE1", "#C2BCF0",
"#DAD6FA", "#EDEBFF", "#F9F9F9")
theme_base <- list(theme_void(base_size = 18) +
theme(plot.margin = margin(10, 10, 10, 10),
plot.title.position = "plot",
plot.title = element_text(margin = margin(t = -4, b = 10),
size = 14, face = "bold")),
guides(fill = "none"))
theme_rank <- c(theme_base,
list(theme(plot.background = element_rect(fill = "#DCBFC9",
color = NA)),
scale_fill_manual(values = reds)))
theme_corr <- c(theme_base,
list(theme(plot.background = element_rect(fill = "#EDDBB6",
color = NA))))
theme_dist <- c(theme_base,
list(theme(plot.background = element_rect(fill = "#D7FBCD",
color = NA))))
theme_other <- c(theme_base,
list(theme(plot.background = element_rect(fill = "#FFE5FF",
color = NA)),
scale_fill_manual(values = purples)))
theme_yaxis <- theme(axis.line.y = element_line(color = "black", size = 1),
axis.ticks.y = element_line(color = "black",
linetype = "solid",
size = 1,
lineend = NULL),
axis.ticks.length.y = unit(0.3, "lines"))
theme_xaxis <- theme(axis.line.x = element_line(color = "black", size = 1),
axis.ticks.x = element_line(color = "black",
linetype = "solid",
size = 1,
lineend = NULL),
axis.ticks.length.x = unit(0.3, "lines"))
theme_border <- theme(plot.background = element_rect(color = "black",
size = 3))
```
## Examining two or more variables
```{r catalogue-two, fig.width = 3, fig.height = 3, echo = FALSE, fig.show='hide'}
ggplot(df2, aes(carat, price)) +
geom_point(color = yellows[1]) +
theme_corr +
theme_yaxis +
theme_xaxis +
theme_border +
ggtitle("SCATTER PLOT")
ggplot(df2, aes(carat, price)) +
geom_hex() +
theme_corr +
theme_yaxis +
theme_xaxis +
theme_border +
scale_fill_gradient(high = "white", low = yellows[1]) +
ggtitle("HEX PLOT")
ggplot(df2, aes(carat, price)) +
geom_density_2d(color = yellows[1]) +
theme_corr +
theme_yaxis +
theme_xaxis +
theme_border +
ggtitle("2D DENSITY PLOT")
ggplot(economics, aes(date, uempmed)) +
geom_line(color = yellows[1]) +
theme_corr +
theme_yaxis +
theme_xaxis +
theme_border +
ggtitle("LINE PLOT")
ggplot(df2, aes(carat, price, size = depth)) +
geom_point(color = yellows[1], alpha = 0.3) +
theme_corr +
theme_yaxis +
theme_xaxis +
theme_border +
ggtitle("BUBBLE CHART") + guides(size = "none")
ggplot(df3, aes(dosef, supp, fill = mlen)) +
geom_tile(color = "black", size = 1.2) +
theme_other +
theme_border +
ggtitle("HEATMAP")
oz_sf %>%
mutate(value = factor(rnorm(n()))) %>%
ggplot(aes(fill = value)) +
geom_sf() +
theme_other +
theme_border +
ggtitle("CHOROPLETH\nMAP")
```
<style>
.catalogue {
margin: 0!important;
width: 18%!important;
margin-right: 2%!important;
}
</style>
`r x<-1:7;paste(glue::glue('<img class="catalogue" src="{fig_path}catalogue-two-{x}.png"/>'), collapse = "")`
Notes:
Let's consider looking at more layers, now with two or more variables.
---
## Illustrative data 💎 diamonds
* Let's have a look at the `diamonds` data which contains information about different attributes of diamonds
```{r}
data(diamonds, package = "ggplot2")
diamonds
```
---
## A scatterplot with `geom_point()`
```{r geom-point}
ggplot(data = diamonds,
mapping = aes(x = carat, y = price)) +
geom_point()
```
* Scatter plot of price vs carat of diamonds
* Each point corresponds to a diamaond
Notes:
* A scatterplot is useful in visualising two numerical variables
* Each point corresponds to an observational unit
* If you have other variables, you may like to map this to other aesthetic values, such as `shape` or `color`.
* When there is a lot of observations, it may be useful to use `alpha` to control the transparency of the points.
---
## A hexagonal 2D heatmap with `geom_hex()`
```{r geom-hex}
ggplot(data = diamonds,
mapping = aes(x = carat, y = price)) +
geom_hex()
```
* A hexagon shows the count of observations within the region.
Notes:
* A hex plot is useful if there is a lot of _overplotting_ in your scatterplot.
* **_Overplotting_** in data visualisation means that the data or labels overlap in the data visualisation making it harder to distinguish individual data points. * Overplotting typically occurs when you have a large dataset.
* A hex plot overcomes the issue by showing the number of observations within a hexagonal area.
* The count is shown by the `fill` in the resulting data visualisation.
---
## A rectangular 2D heatmap with `geom_bin_2d()`
```{r geom-bin2d}
ggplot(data = diamonds,
mapping = aes(x = carat, y = price)) +
geom_bin_2d()
```
Notes:
* `geom_bin_2d()` is the same as `geom_hex()` but the shape is a rectangle instead of a hexagon.
---
## Count of overlapping points with `geom_count()`
```{r geom-count}
ggplot(data = diamonds,
mapping = aes(x = carat, y = price)) +
geom_count()
```
Notes:
* `geom_count()` counts the number of points in the same location
* The count is then mapped to the aesthetic `size`.
---
## Contour of a 2D density with `geom_density_2d()`
```{r geom-density-2d}
ggplot(data = diamonds,
mapping = aes(x = carat, y = price)) +
geom_density_2d()
```
Notes:
* If you have want to visualise the joint density of two variables then `geom_density_2d()` is useful.
* The axis shows the density of the corresponding variable.
* The 2D density is estimated using `MASS::kde2d()`.
---
## Contour of a 2D density with `geom_density_2d_filled()`
```{r geom-density-2d-filled}
ggplot(data = diamonds,
mapping = aes(x = carat, y = price)) +
geom_density_2d_filled()
```
Notes:
* `geom_density_2d()` draws the contour line
* `geom_density_2d_filled()` draws the contour bands
---
## Illustrative data ⛰️ volcano
* The data contains topographic information on Auckland's Maunga Whau Volcano
```{r}
volcanod <- data.frame(row = as.vector(row(volcano)),
col = as.vector(col(volcano)),
value = as.vector(volcano))
volcanod
```
Notes:
* The original data is a matrix and we must wrangle in the form ready for `ggplot` first.
---
## A 2D contour plot with `geom_contour()`
```{r geom-contour}
ggplot(data = volcanod,
mapping = aes(x = col, y = row, z = value)) +
geom_contour()
```
---
## A 2D contour plot with `geom_contour_filled()`
```{r geom-contour-filled}
ggplot(data = volcanod,
mapping = aes(x = col, y = row, z = value)) +
geom_contour_filled()
```
---
## Tile plots with `geom_tile()`
```{r geom-tile}
ggplot(volcanod, aes(col, row, fill = value)) +
geom_tile()
```
---
## Raster plots with `geom_raster()`
```{r geom-raster}
ggplot(volcanod, aes(col, row, fill = value)) +
geom_raster()
```
* A high performance special case of `geom_tile()` for when the tiles are the same size
---
## Rectangular plots with `geom_rect()`
```{r geom-rect}
ggplot(volcanod, aes(xmin = col - 0.5, xmax = col + 0.5,
ymin = row - 0.5, ymax = row + 0.5, fill = value)) +
geom_rect()
```
* A reparameterised version of `geom_tile()`
---
## Illustrative data 📈 economics
```{r}
data(economics, package = "ggplot2")
economics
```
---
## Line plot with `geom_line()`
```{r geom-line}
ggplot(economics, aes(date, unemploy)) +
geom_line()
```
---
## `geom_path()`
```{r geom-path}
ggplot(economics, aes(unemploy/pop, psavert)) +
geom_path()
```
---
## `geom_step()`
```{r geom-step}
ggplot(economics, aes(unemploy/pop, psavert)) +
geom_step()
```
---
## Drawing maps
* Drawing maps require the map data
```{r}
world <- map_data("world")
world
```
---
## Drawing world map with `geom_polygon()`
```{r geom-polygon}
world <- map_data("world")
ggplot(world, aes(long, lat, group = group)) +
geom_polygon()
```
---
## Position adjustments
```{r catalogue-position, fig.width = 3, fig.height = 3, echo = FALSE, fig.show='hide'}
ggplot(sumdf2, aes(g1, y, fill = g2)) +
geom_col() +
theme_rank +
theme_yaxis +
theme_border +
ggtitle("STACKED\nBARPLOT")
ggplot(sumdf2, aes(g1, y, fill = g2)) +
geom_col(position = "dodge") +
theme_rank +
theme_yaxis +
theme_border +
ggtitle("GROUPED\nBARPLOT")
ggplot(sumdf2, aes(g1, y, fill = g2)) +
geom_col(position = "fill") +
theme_rank +
theme_yaxis +
theme_border +
ggtitle("STACKED\nPERCENTAGE\nBARPLOT")
```
`r x<-1:3;paste(glue::glue('<img class="catalogue" src="{fig_path}catalogue-position-{x}.png"/>'), collapse = "")`
---
## Other layers
* There are more layers in `ggplot`!
* We won't cover the layers provided via functions starting with `stat_` but there are plenty of examples in the wild.
* There are also many extension packages to draw more plots: https://exts.ggplot2.tidyverse.org/gallery/
* It is normal to google and copy-and-paste code that you find on the web.
* `ggplot2` is also [continually updated](https://github.com/tidyverse/ggplot2/blob/main/NEWS.md) so some new features may be added in the future.
---
## Illustrative data 🚢 ship accidents
```{r}
data(Accident, package = "Ecdat")
str(Accident)
```
Notes:
* `type` is the ship type
* `constr` is year constructed
* `operate` is the year operated
* `months` is the service amount counted in months
* `acc` is the number of accidents.
---
## A stacked barplot with `geom_col()`
```{r geom-col-stack}
ggplot(Accident, aes(type, acc, fill = constr, group = operate)) +
geom_col(color = "black", position = "stack")
```
Notes:
* Recall that `geom_col()` is the same as `geom_bar()` except `stat="identity"`, i.e. your input data should already be summarised as count data.
* By default the values in `y` are stacked on top of another.
* The aesthetic `group` here breaks the count in two groups and stack one on top of the other (try running the code without `group = operate`).
---
## A grouped barplot with `geom_col()`
```{r geom-col-dodge}
ggplot(Accident, aes(type, acc, fill = constr)) +
geom_col(color = "black", position = "dodge")
```
Notes:
* Notice here we removed the `group = operate` -- this results in stacked bars for the same `type` and `fill`.
* Here the `x` values are recalculated so that the factor levels within the same group (as determined by `x`) can fit.
---
## Another grouped barplot with `geom_col()`
```{r geom-col-dodge2}
ggplot(Accident, aes(type, acc, fill = constr, group = operate)) +
geom_col(color = "black", position = "dodge2")
```
Notes:
* Can you see what changed?
* `position = "dodge"` doesn't deal well when there is `fill` and `group` together but you can use `position = "dodge2"` that recalculates the `x` values in another way.
---
## Stacked percentage barplot with `geom_col()`
```{r geom-col-fill}
ggplot(Accident, aes(type, acc, fill = constr, group = operate)) +
geom_col(color = "black", position = "fill")
```
Notes:
* If you want to compare the percentages between the different `x`, then `position = "fill"` can be handy.
---
## Summary
* We looked at more layers in `ggplot2`.
* There are other layers available beyond `ggplot2` in [extension packages](https://github.com/tidyverse/ggplot2/blob/main/NEWS.md).
* It's perfectly normal that you need to google how to use `ggplot` for certain plots (we all do in the beginning).
* We also saw how to use the different `position` adjustments for barplots.