-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy path04-annotation.Rmd
729 lines (608 loc) · 17.1 KB
/
04-annotation.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
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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
---
title: "Segment 4: Provide Context with Annotations"
description: "Part 3 of the Pearson Live Training Session “Hands–On Data Visualization with ggplot2” for O’Reilly"
author:
- name: Cédric Scherer
url: https://cedricscherer.com
output:
distill::distill_article:
toc: true
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, warning = FALSE, message = FALSE,
fig.width = 10, fig.height = 6, fig.retina = 2,
dev = "ragg_png", res = 1000)
```
```{r preparation}
library(tidyverse)
theme_set(theme_light(base_size = 18))
data <- readr::read_csv("https://raw.githubusercontent.com/z3tt/hands-on-ggplot2/main/data/crypto_cleaned.csv")
```
## Titles, Labels & Co
### Labels: `labs() `
To change the labels and add a title, a subtitle, a caption and/or a tag, use `labs()`:
```{r structure-labs}
ggplot(data, aes(date, close, color = currency)) +
geom_line() +
labs(x = NULL, y = "Closing Price", color = "Cryptocurrency:")
```
There are multiple ways to add labels:
```{r structure-labs-alt}
ggplot(data, aes(date, close, color = currency)) +
geom_line() +
xlab(NULL) +
# scale_x_date(name = NULL) +
ylab("Closing Price") +
# scale_y_continuous(name = "Closing Price") +
scale_color_discrete(name = "Cryptocurrency:")
```
To change the labels and add a title, a subtitle, a caption and/or a tag, use `labs()`:
```{r structure-titles}
ggplot(data, aes(date, close, color = currency)) +
geom_line() +
labs(x = NULL, y = "Closing Price", color = "Cryptocurrency:",
title = "Performance of the Top 4 Cryptocurrencies", caption = "Data: CoinMarketCap.com",
subtitle = "The time series show daily closing prices from 2018 to 2020.", tag = "A)")
```
### Plot Position
```{r boxplot-title-position-panel}
ggplot(data, aes(close, currency)) +
geom_boxplot() +
ggtitle("Closing Prices of the Top 4 Cryptocurrencies, 2018–2020") +
theme(plot.title.position = "panel")
```
```{r boxplot-title-position-plot}
ggplot(data, aes(close, currency)) +
geom_boxplot() +
ggtitle("Closing Prices of the Top 4 Cryptocurrencies, 2018–2020") +
theme(plot.title.position = "plot")
```
### Text Rendering with `{ggtext} `
The `{ggtext}` package provides simple Markdown and HTML rendering for `{ggplot2}`.
```{r ggtext-showcase-raw}
#install.packages("ggtext")
library(ggtext)
ggplot(data, aes(date, close, color = currency)) +
geom_line() +
labs(title = "Performance of the **Top 4 Cryptocurrencies**", caption = "Data: *CoinMarketCap.com*")
```
```{r ggtext-showcase}
ggplot(data, aes(date, close, color = currency)) +
geom_line() +
labs(title = "Performance of the **Top 4 Cryptocurrencies**", caption = "Data: *CoinMarketCap.com*") +
theme(plot.title = element_markdown(), plot.caption = element_markdown())
```
```{r ggtext-showcase-2}
ggplot(data, aes(date, close, color = currency)) +
geom_line() +
labs(title = "Performance of the <b style='font-size:34pt;'>Top 4 Cryptocurrencies ",
caption = "<span style='color:firebrick;'>Data:</span> <i>CoinMarketCap.com</i>") +
theme(plot.title = element_markdown(), plot.caption = element_markdown())
```
`element_textbox` and `element_textbox_simple` automatically wrap long text:
```{r ggtext-wrap-title}
ggplot(data, aes(date, close, color = currency)) +
geom_line() +
labs(title = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Accumsan tortor posuere ac ut consequat semper viverra nam libero.") +
theme(plot.title = element_textbox_simple())
```
```{r ggtext-wrap-title-2}
ggplot(data, aes(date, close, color = currency)) +
geom_line() +
labs(title = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Accumsan tortor posuere ac ut consequat semper viverra nam libero.") +
theme(plot.title = element_textbox_simple(margin = margin(b = 15), lineheight = .9))
```
```{r ggtext-wrap-title-3}
ggplot(data, aes(date, close, color = currency)) +
geom_line() +
labs(title = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Accumsan tortor posuere ac ut consequat semper viverra nam libero.") +
theme(plot.title = element_textbox_simple(margin = margin(b = 15), lineheight = .9,
linetype = 1, padding = margin(rep(10, 4))))
```
```{r ggtext-wrap-title-4}
ggplot(data, aes(date, close, color = currency)) +
geom_line() +
labs(title = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Accumsan tortor posuere ac ut consequat semper viverra nam libero.") +
theme(plot.title = element_textbox_simple(margin = margin(b = 15), lineheight = .9,
linetype = 1, padding = margin(rep(10, 4)),
r = unit(10, "pt"), fill = "moccasin"))
```
## Basic Text Labelling
### Annotations via `annotate() `
The `annotate()` function allows to add geom's to a plot without mapping to variables to aesthetics:
```{r annotate-text}
ggplot(data, aes(close, open)) +
geom_point(size = 2) +
annotate(
geom = "text",
x = 250,
y = 50,
label = "Some\nadditional\ntext"
)
```
```{r annotate-text-adj}
ggplot(data, aes(close, open)) +
geom_point(size = 2) +
annotate(
geom = "text",
x = 250,
y = 50,
label = "Some\nadditional\ntext",
size = 6,
color = "firebrick",
fontface = "bold",
lineheight = .9
)
```
```{r annotate-box}
ggplot(data, aes(close, open)) +
geom_point(size = 2) +
annotate(
geom = "rect",
xmin = 150,
xmax = Inf,
ymin = 150,
ymax = Inf,
fill = "firebrick"
)
```
The `annotate()` function also allows to add geom's to a plot without mapping to variables to aesthetics:
```{r annotate-box-adj}
ggplot(data, aes(close, open)) +
annotate(
geom = "rect",
xmin = 150,
xmax = Inf,
ymin = 150,
ymax = Inf,
fill = "firebrick"
) +
geom_point(size = 2)
```
```{r annotate-text-line}
ggplot(data, aes(close, open)) +
geom_point(size = 2) +
annotate(
geom = "text",
x = 250, y = 50,
label = "Some\nadditional\ntext",
size = 6,
lineheight = .9
) +
annotate(
geom = "line",
x = 250, y = 75,
xend = 180, yend = 160
)
```
```{r annotate-text-curve}
ggplot(data, aes(close, open)) +
geom_point(size = 2) +
annotate(
geom = "text",
x = 250, y = 50,
label = "Some\nadditional\ntext",
size = 6,
lineheight = .9
) +
annotate(
geom = "curve",
x = 250, y = 75,
xend = 180, yend = 160
)
```
```{r annotate-text-arrow}
ggplot(data, aes(close, open)) +
geom_point(size = 2) +
annotate(
geom = "text",
x = 250, y = 50,
label = "Some\nadditional\ntext",
size = 6,
lineheight = .9
) +
annotate(
geom = "curve",
x = 250, y = 75,
xend = 180, yend = 160,
curvature = .4,
arrow = arrow()
)
```
```{r annotate-text-arrow-type2}
ggplot(data, aes(close, open)) +
geom_point(size = 2) +
annotate(
geom = "text",
x = 250, y = 50,
label = "Some\nadditional\ntext",
size = 6,
lineheight = .9
) +
annotate(
geom = "curve",
x = 250, y = 75,
xend = 180, yend = 160,
curvature = .4,
arrow = arrow(length = unit(0.4, "lines"),
type = "closed",
ends = "both")
)
```
```{r annotate-text-arrow-skewed}
ggplot(data, aes(close, open)) +
geom_point(size = 2) +
annotate(
geom = "text",
x = 250, y = 50,
label = "Some\nadditional\ntext",
size = 6,
lineheight = .9
) +
annotate(
geom = "curve",
x = 250, y = 75,
xend = 180, yend = 160,
curvature = .8,
angle = 130,
arrow = arrow(length = unit(0.4, "lines"),
type = "closed",
ends = "both")
)
```
---
## Exercise 1:
* Create the following visualization:

---
### Annotations via `geom_text|label() `
You already know `geom_text()`:
```{r geom-text}
ggplot(data, aes(close, open)) +
geom_point(size = 2) +
geom_text(
aes(label = currency),
size = 5
)
```
Let's tag only those days that are considerably far from the diagonal:
```{r geom-text-outlier-data}
outliers <- data %>%
mutate(dist = abs(close - open) / sqrt(2)) %>%
filter(dist > 20)
```
```{r geom-text-outlier-data-output}
outliers <- data %>%
mutate(dist = abs(close - open) / sqrt(2)) %>%
filter(dist > 20)
outliers
```
We can use both data sets in the same ggplot:
```{r geom-text-outlier}
ggplot(outliers, aes(close, open)) +
geom_point(data = data, color = "grey80") +
geom_point(size = 2) +
geom_text(
aes(label = currency),
size = 5
)
```
We can offset the labels with the help of the nudge arguments:
```{r geom-text-outlier-adj}
ggplot(outliers, aes(close, open)) +
geom_point(data = data, color = "grey80") +
geom_point(size = 2) +
geom_text(
aes(label = currency),
size = 5,
hjust = 0,
nudge_x = 5,
nudge_y = -5
)
```
```{r geom-text-outlier-adj-limits}
ggplot(outliers, aes(close, open)) +
geom_point(data = data, color = "grey80") +
geom_point(size = 2) +
geom_text(
aes(label = currency),
size = 5,
hjust = 0,
nudge_x = 5,
nudge_y = -5
) +
scale_x_continuous(
limits = c(NA, 320)
)
```
## Advanced Text Labelling
### Annotations via `geom\_text|label\_repel() `
The `{ggrepel}` package provides two geom's to repel overlapping text labels
```{r geom-text-repel}
#install.packages("ggrepel")
ggplot(outliers, aes(close, open)) +
geom_point(data = data, color = "grey80") +
geom_point(size = 2) +
ggrepel::geom_text_repel(
aes(label = currency),
size = 5,
hjust = 0
)
```
```{r geom-label-repel-adj}
#install.packages("ggrepel")
ggplot(outliers, aes(close, open)) +
geom_point(data = data, color = "grey80") +
geom_point(size = 2) +
ggrepel::geom_label_repel(
aes(label = currency),
size = 5,
## space between points + labels
box.padding = .5,
## always draw segments
min.segment.length = 0
)
```
## Annotations via `geom\_mark\_*() `
For illustration purposes we use a data set about Palmer penguins (Horst, Hill & Gorman 2020).
```{r penguin-scatter}
penguins <- read_csv(
here::here("data", "penguins.csv")
)
(g <-
ggplot(
penguins,
aes(flipper_length_mm, bill_length_mm,
color = species)
) +
geom_point(show.legend = FALSE)
)
```
The `{ggforce}` package provides functionality to highlight groups:
```{r geom-mark-ellipse}
#install.packages("ggforce")
g +
ggforce::geom_mark_ellipse(
aes(label = species)
)
```
```{r geom-mark-ellipse-desc-adj}
g +
ggforce::geom_mark_ellipse(
aes(label = species)
) +
coord_cartesian(
xlim = c(160, 250),
ylim = c(20, 70)
)
```
```{r plot-geom-mark-ellipse-desc-adj, ref.label="geom-mark-ellipse-desc-adj", echo=FALSE, fig.width=14, fig.height=8}
```
```{r geom-mark-ellipse-desc}
g +
ggforce::geom_mark_ellipse(
aes(label = species,
description = latin_name)
) +
coord_cartesian(
xlim = c(160, 250),
ylim = c(20, 70)
)
```
```{r geom-mark-ellipse-filter}
g +
ggforce::geom_mark_ellipse(
aes(label = species,
filter = species == "Adelie")
) +
coord_cartesian(
xlim = c(165, NA),
ylim = c(25, NA)
) +
theme(legend.position = "none")
```
```{r geom-mark-circle-filter}
g +
ggforce::geom_mark_circle(
aes(label = species,
filter = species == "Adelie")
) +
coord_cartesian(
xlim = c(165, NA),
ylim = c(25, NA)
) +
theme(legend.position = "none")
```
```{r geom-mark-rect-filter}
g +
ggforce::geom_mark_rect(
aes(label = species,
filter = species == "Adelie")
) +
coord_cartesian(
xlim = c(165, NA),
ylim = c(25, NA)
) +
theme(legend.position = "none")
```
```{r geom-mark-hull-filter}
g +
ggforce::geom_mark_hull(
aes(label = species,
filter = species == "Adelie")
) +
coord_cartesian(
xlim = c(165, NA),
ylim = c(25, NA)
) +
theme(legend.position = "none")
```
## Add Images
### Add Images via `annotation_custom() `
`magick::image_read()` allows to directly store images from the web in `R`:
```{r annotation-custom-img-prep}
#install.packages("magick")
url <- "https://image.shutterstock.com/image-vector/set-gold-silver-crypto-currencies-260nw-775898248.jpg"
img <- magick::image_read(url)
img
```
`annotation_custom()` in combination with `grid::rasterGrob()` allows to add images:
```{r annotation-custom-img}
ggplot(data, aes(date, close, color = currency)) +
annotation_custom(
grid::rasterGrob(
image = img
)
) +
geom_line(size = .8)
```
```{r annotation-custom-img-mod}
ggplot(data, aes(date, close, color = currency)) +
annotation_custom(
grid::rasterGrob(
image = img,
width = unit(.4, "npc")
)
) +
geom_line(size = .8)
```
```{r annotation-custom-img-mod2}
ggplot(data, aes(date, close, color = currency)) +
annotation_custom(
grid::rasterGrob(
image = img,
x = .5,
y = .9,
width = .9
)
) +
geom_line(size = .8)
```
```{r annotation-custom-img-below}
ggplot(data, aes(date, close, color = currency)) +
annotation_custom(
grid::rasterGrob(
image = img,
x = .5,
y = -.25,
width = .9
)
) +
geom_line(size = .8) +
coord_cartesian(clip = "off") +
theme(plot.margin = margin(12, 12, 130, 12))
```
### Add Images with the `{cowplot} `Package
The `cowplot` package can also be used to add images:
```{r cowplot-img}
#install.packages("cowplot")
g <- ggplot(data, aes(close, open)) +
geom_point(alpha = .4) +
theme(plot.margin = margin(12, 12, 70, 12))
cowplot::ggdraw(g) +
cowplot::draw_image(
img,
scale = 1
)
```
```{r cowplot-img-2}
g <- ggplot(data, aes(close, open)) +
geom_point(alpha = .4) +
theme(panel.background = element_blank(),
plot.background = element_blank())
cowplot::ggdraw() +
cowplot::draw_image(
img,
scale = 1
) +
cowplot::draw_plot(g)
```
```{r cowplot-img-3}
g <- ggplot(data, aes(close, open)) +
geom_point(alpha = .4) +
theme(plot.margin = margin(12, 12, 45, 12))
url <- "https://upload.wikimedia.org/wikipedia/en/thumb/3/35/Pearson_logo.svg/1280px-Pearson_logo.svg.png"
logo <- magick::image_read(url)
cowplot::ggdraw(g) +
cowplot::draw_image(
logo,
scale = .2,
x = 1,
hjust = 1,
halign = 1,
valign = 0
)
```
---
## Exercise 2:
* Play around with the two different approaches and how they differ in placing and scaling the images.
* **Bonus:** Write a function that lets you add your company's logo to a ggplot object.
---
## Resources
* Chapter 8 [Annotations](https://ggplot2-book.org/annotations.html) of the “ggplot2” book by Hadley Wickham et al.
* Chapter 7 [Annotations](https://r-graphics.org/chapter-annotate) of the “R Graphics Cookbook” book by Winston Chang
* [“Add a Logo to Your Plot”](https://themockup.blog/posts/2019-01-09-add-a-logo-to-your-plot/), blog post by Thomas Mock
* [“How to Add a Logo to ggplot by Magick”](https://www.danielphadley.com/ggplot-logo/), blog post by Daniel Hadley
* [“A `{ggplot2}` Tutorial for Beautiful Plotting in R”](https://www.cedricscherer.com/2019/08/05/a-ggplot2-tutorial-for-beautiful-plotting-in-r/), my extensive "how to"-tutorial
---
## Appendix
### Annotations with `{ggtext} `
The `{ggtext}` package also comes with two geom's: `geom_richtext()` and `geom_textbox()`:
```{r ggtext-richtext}
ggplot(data, aes(close, open)) +
geom_point(size = 2) +
geom_richtext(
aes(
x = 250, y = 50,
label = "Some **additional** text"
),
stat = "unique"
)
```
```{r ggtext-richtext-2}
ggplot(data, aes(close, open)) +
geom_point(size = 2) +
geom_richtext(
aes(
x = 250, y = 50,
label = "Some **additional** text"
),
stat = "unique",
color = "firebrick",
size = 5,
fill = NA,
label.color = NA
)
```
```{r ggtext-textbox}
ggplot(data, aes(close, open)) +
geom_point(size = 2) +
geom_textbox(
aes(
x = 210, y = 50,
label = "**Lorem ipsum** dolor sit amet, *consectetur adipiscing elit,* sed do eiusmod tempor incididunt ut labore et dolore <span style='color:red;'>magna</span> aliqua. *Accumsan tortor posuere ac ut consequat semper* ***viverra nam libero.***"
),
stat = "unique"
)
```
```{r ggtext-textbox-width}
ggplot(data, aes(close, open)) +
geom_point(size = 2) +
geom_textbox(
aes(
x = 210, y = 50,
label = "**Lorem ipsum** dolor sit amet, *consectetur adipiscing elit,* sed do eiusmod tempor incididunt ut labore et dolore <span style='color:red;'>magna</span> aliqua. *Accumsan tortor posuere ac ut consequat semper* ***viverra nam libero.***"
),
stat = "unique",
width = unit(15, "lines")
)
```
---
## Session Info
<details><summary>Expand for details</summary>
```{r sessionInfo, echo = F}
Sys.time()
git2r::repository()
sessionInfo()
```
</details>