-
Notifications
You must be signed in to change notification settings - Fork 1
/
09_ggplot2.Rmd
924 lines (752 loc) · 25.7 KB
/
09_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
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
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
---
title: "09_ggplot2"
output: html_document
---
class: middle, center, inverse
layout: false
# 4.7 `ggplot2`:<br><br>Create Elegant Data Visualisations<br>Using the Grammar of Graphics
---
background-image: url(https://raw.githubusercontent.com/tidyverse/ggplot2/master/man/figures/logo.png)
background-position: 97.5% 2.5%
background-size: 7.5%
layout: true
---
## 4.7 `ggplot2`: Elegant Data Visualisations
`ggplot2` is Hadley Wickham's [reimplementation](https://www.tandfonline.com/doi/abs/10.1198/jcgs.2009.07098) of the 2005 published *The Grammar of Graphics* by Leland Wilkinson. It provides a large amount of functions for generating high-quality graphs in a layer-based fashion and has even sparked a whole ecosystem of 'gg'-style visualization packages.
<br>
```{r, echo=F, out.width='75%', fig.align='center'}
knitr::include_graphics("./img/grammar-of-graphic-layers.png")
```
.center[
*Src: [towardsdatascience](https://towardsdatascience.com/a-comprehensive-guide-to-the-grammar-of-graphics-for-effective-visualization-of-multi-dimensional-1f92b4ed4149)*
]
???
- Where `dplyr` provides a grammar for data manipulation, `ggplot2` does the same for plotting
- Up to now, most likely the `graphics` package included in base `R` was your go-to address for crafting visualisations (`plot()`, `hist()`, `boxplot()`).
---
## 4.7 `ggplot2`: Elegant Data Visualisations
```{r, echo=F, out.height='60%', out.width='60%', fig.align='center'}
knitr::include_graphics("https://raw.githubusercontent.com/allisonhorst/stats-illustrations/master/rstats-artwork/ggplot2_masterpiece.png")
```
---
## 4.7 `ggplot2`: Elegant Data Visualisations
**Data:** The data set (usually a `tibble`) from which to select the variables that are about to be plotted. It is specified by the first argument in `ggplot()` and thus predestined to be piped into our plot pipeline.
.pull-left[
**Univariate example:**
```{r p_step_u1, eval=F}
penguins %>%
ggplot(data = .) # equivalent to: ggplot
```
]
.pull-right[
```{r ref.label='p_step_u1', echo=F, fig.width=8, fig.asp=0.618, fig.retina=3, fig.align='center'}
```
]
.footnote[
*Note: A compact go-to-guide for data visualisations with `ggplot2` is the official [cheat sheet](https://raw.githubusercontent.com/rstudio/cheatsheets/master/data-visualization.pdf).*
]
---
## 4.7 `ggplot2`: Elegant Data Visualisations
**Aesthetics:** Mappings that describe how variables in the data are mapped to aesthetic attributes in the plot, such as axes, shapes, sizes or colors.
.pull-left[
**Univariate example:**
```{r p_step_u2, eval=F}
penguins %>%
ggplot(aes(x = flipper_length_mm))
```
]
.pull-right[
```{r ref.label='p_step_u2', echo=F, fig.width=8, fig.asp=0.618, fig.retina=3, fig.align='center'}
```
]
???
- You can already see that `ggplot2` extracts the ranges in your variables.
---
## 4.7 `ggplot2`: Elegant Data Visualisations
**Geoms:** Geometric objects that determine your overall plot type, e.g., bar, lines, points or boxplots. They specify the graphical representation of your data.
.pull-left[
**Univariate example:**
```{r p_step_u3, eval=F}
penguins %>%
ggplot(aes(x = flipper_length_mm)) +
geom_histogram(na.rm = TRUE)
```
`ggplot2` comes with decent default settings. Each `geom_*()` has its own options for customizing the geom, e.g.,
- change the number of bins with the `bins` argument,
- change the width of the bins with `binwidth` argument.
]
.pull-right[
```{r ref.label='p_step_u3', echo=F, fig.width=8, fig.asp=0.618, fig.retina=3, fig.align='center', message=F}
```
]
???
Note that ggplots are constructed by adding layers with `+` instead of ` %>% `
---
## 4.7 `ggplot2`: Elegant Data Visualisations
**Geoms:** Geometric objects that determine your overall plot type, e.g., bar, lines, points or boxplots. They specify the graphical representation of your data.
.pull-left[
**Univariate example:**
```{r p_step_u4, eval=F}
penguins %>%
ggplot(aes(x = flipper_length_mm)) +
geom_bar(na.rm = TRUE)
```
Eventually, you may realize the beauty of the `geom_*()` layers. They do all the required calculations for you!
This is due to the frequently overlooked `stat` argument (which defaults to `stat = "count"` for the `geom_bar()` layer).
]
.pull-right[
```{r ref.label='p_step_u4', echo=F, fig.width=8, fig.asp=0.618, fig.retina=3, fig.align='center'}
```
]
---
## 4.7 `ggplot2`: Elegant Data Visualisations
**Stats:** Statistical transformations provide a summary of the data. They can be used to transform a given variable without changing the plot type (i.e. geom).
.pull-left[
**Univariate example:**
```{r p_step_u5, eval=F}
penguins %>%
ggplot(aes(x = flipper_length_mm)) +
geom_bar(na.rm = TRUE, stat = "density")
```
Most of the time you will just plot the data as-is (`stat = "identity"`). As soon as you require some form of statistical transformation (e.g., count, density or unique) before plotting, the `stat` argument can handle this for you.
]
.pull-right[
```{r ref.label='p_step_u5', echo=F, fig.width=8, fig.asp=0.618, fig.retina=3, fig.align='center'}
```
]
???
- you can also do all the transformations beforehand using `group_by` and `summarise`
---
## 4.7 `ggplot2`: Elegant Data Visualisations
**Stats:** Statistical transformations provide a summary of the data. They can be used to transform a given variable without changing the plot type (i.e. geom).
.pull-left[
**Univariate example:**
```{r p_step_u6, eval=F}
penguins %>%
ggplot(aes(x = flipper_length_mm)) +
geom_density(na.rm = TRUE)
```
If you have to manually change the default setting of the `stat` argument, it is likely that `ggplot2` has implemented a corresponding `geom_*()` already.
]
.pull-right[
```{r ref.label='p_step_u6', echo=F, fig.width=8, fig.asp=0.618, fig.retina=3, fig.align='center'}
```
]
.footnote[
.pull-left[
*Note: For a great explanation of the inner workings of the `stat` layer, see this [blog post](https://yjunechoe.github.io/posts/2020-09-26-demystifying-stat-layers-ggplot2/) by June Choe.*
]]
---
## 4.7 `ggplot2`: Elegant Data Visualisations
**Data:** The data set (usually a `tibble`) from which to select the variables that are about to be plotted. It is specified by the first argument in `ggplot()` and thus predestined to be piped into our plot pipeline.
.pull-left[
**Bivariate example:**
```{r p_step_b1, eval=F}
penguins %>%
ggplot
```
]
.pull-right[
```{r ref.label='p_step_b1', echo=F, fig.width=8, fig.asp=0.618, fig.retina=3, fig.align='center'}
```
]
---
## 4.7 `ggplot2`: Elegant Data Visualisations
**Aesthetics:** Mappings that describe how variables in the data are mapped to aesthetic attributes in the plot, such as axes, shapes, sizes or colors.
.pull-left[
**Bivariate example:**
```{r p_step_b2, eval=F}
penguins %>%
ggplot(aes(x = flipper_length_mm,
y = body_mass_g))
```
]
.pull-right[
```{r ref.label='p_step_b2', echo=F, fig.width=8, fig.asp=0.618, fig.retina=3, fig.align='center'}
```
]
---
## 4.7 `ggplot2`: Elegant Data Visualisations
**Geoms:** Geometric objects that determine your overall plot type, e.g., bar, lines, points or boxplots. They specify the graphical representation of your data.
.pull-left[
**Bivariate example:**
```{r p_step_b3, eval=F}
penguins %>%
ggplot(aes(x = flipper_length_mm,
y = body_mass_g)) +
geom_point(na.rm = TRUE)
```
]
.pull-right[
```{r ref.label='p_step_b3', echo=F, fig.width=8, fig.asp=0.618, fig.retina=3, fig.align='center'}
```
]
---
## 4.7 `ggplot2`: Elegant Data Visualisations
There are multiple ways of changing the color, shape or size aesthetics. Remember that using the `aes()` argument **maps** variable values to your aesthetic. The behavior differs for discrete vs. continuous variables.
.pull-left[
**Bivariate example:**
```{r p_step_b4, eval=F}
penguins %>%
ggplot(aes(x = flipper_length_mm,
y = body_mass_g)) +
geom_point(aes(color = species),
na.rm = TRUE)
```
]
.pull-right[
```{r ref.label='p_step_b4', echo=F, fig.width=8, fig.asp=0.618, fig.retina=3, fig.align='center'}
```
]
---
## 4.7 `ggplot2`: Elegant Data Visualisations
There are multiple ways of changing the color, shape or size aesthetics. Remember that using the `aes()` argument **maps** variable values to your aesthetic. The behavior differs for discrete vs. continuous variables.
.pull-left[
**Bivariate example:**
```{r p_step_b5, eval=F}
penguins %>%
ggplot(aes(x = flipper_length_mm,
y = body_mass_g)) +
geom_point(aes(color = bill_depth_mm),
na.rm = TRUE)
```
]
.pull-right[
```{r ref.label='p_step_b5', echo=F, fig.width=8, fig.asp=0.618, fig.retina=3, fig.align='center'}
```
]
---
## 4.7 `ggplot2`: Elegant Data Visualisations
By specifying the `color` argument outside of the `aes()` argument, we **set** the color without considering the values of any other variable.
.pull-left[
**Bivariate example:**
```{r p_step_b6, eval=F}
penguins %>%
ggplot(aes(x = flipper_length_mm,
y = body_mass_g)) +
geom_point(color = "red",
na.rm = TRUE)
```
For truly customized colors you may refer to [HTML color codes](https://www.w3schools.com/colors/colors_picker.asp) (also called *hex codes*, e.g., `#ff0000` for red) instead of specifying colors by their [predefined name](http://sape.inf.usi.ch/quick-reference/ggplot2/colour) in `R`.
]
.pull-right[
```{r ref.label='p_step_b6', echo=F, fig.width=8, fig.asp=0.618, fig.retina=3, fig.align='center'}
```
]
???
Remember:
- if something is specified inside of `aes` it is mapped, i.e. the characteristic depends on the data
- if something is specified outside of `aes`, it is assigned rather manually
- hexcodes: codes specifying the level of red (first two), green (second two) and blue (last two digits) color intensity
---
## 4.7 `ggplot2`: Elegant Data Visualisations
We can do the same in order to change the `shape` and `size` of our data points. Either by mapping them to the values of another variable or by setting them manually outside of the `aes()` argument.
.pull-left[
**Bivariate example:**
```{r p_step_b7a, eval=F}
penguins %>%
ggplot(aes(x = flipper_length_mm,
y = body_mass_g)) +
geom_point(aes(shape = species),
size = 4,
na.rm = TRUE)
```
`ggplot2` provides 24 available shapes for customizing your plot (see [shape overview](https://ggplot2.tidyverse.org/reference/scale_shape-6.png)).
]
.pull-right[
```{r ref.label='p_step_b7a', echo=F, fig.width=8, fig.asp=0.618, fig.retina=3, fig.align='center'}
```
]
---
## 4.7 `ggplot2`: Elegant Data Visualisations
We can do the same in order to change the `shape` and `size` of our data points. Either by mapping them to the values of another variable or by setting them manually outside of the `aes()` argument.
.pull-left[
**Bivariate example:**
```{r p_step_b7b, eval=F}
penguins %>%
ggplot(aes(x = flipper_length_mm,
y = body_mass_g)) +
geom_point(aes(shape = species,
size = bill_depth_mm),
na.rm = TRUE)
```
]
.pull-right[
```{r ref.label='p_step_b7b', echo=F, fig.width=8, fig.asp=0.618, fig.retina=3, fig.align='center'}
```
]
---
## 4.7 `ggplot2`: Elegant Data Visualisations
**Facets:** Facets split the plot into multiple subplots based on the levels of one or more factor variables.
.pull-left[
**Bivariate example:**
```{r p_step_b8, eval=F}
penguins %>%
ggplot(aes(x = flipper_length_mm,
y = body_mass_g)) +
geom_point(aes(shape = species),
na.rm = TRUE) +
facet_wrap(~ year)
```
]
.pull-right[
```{r ref.label='p_step_b8', echo=F, fig.width=8, fig.asp=0.618, fig.retina=3, fig.align='center'}
```
]
---
## 4.7 `ggplot2`: Elegant Data Visualisations
**Facets:** Facets split the plot into multiple subplots based on the levels of one or more factor variables.
.pull-left[
**Bivariate example:**
```{r p_step_b9, eval=F}
penguins %>%
ggplot(aes(x = flipper_length_mm,
y = body_mass_g)) +
geom_point(aes(shape = species),
na.rm = TRUE) +
facet_wrap(~ year + island)
```
]
.pull-right[
```{r ref.label='p_step_b9', echo=F, fig.width=8, fig.asp=0.618, fig.retina=3, fig.align='center'}
```
]
???
- lets go back to one of the previous plots
---
## 4.7 `ggplot2`: Elegant Data Visualisations
**Scales:** Scales control the aesthetic mappings by overriding the *default* settings. For example, they allow to refine the presentation of x- and y-axis, labels or color palettes ex post.
.pull-left[
**Bivariate example:**
```{r p_step_b10, eval=F}
penguins %>%
ggplot(aes(x = flipper_length_mm,
y = body_mass_g)) +
geom_point(aes(color = species),
size = 3, na.rm = TRUE) +
scale_colour_brewer(palette = "Set3")
```
The family of `scale_colour_*()` functions enables you to adjust the values of your `color` aesthetic (e.g., `scale_colour_brewer()` selects a palette from the famous [ColorBrewer](https://colorbrewer2.org/#type=sequential&scheme=BuGn&n=3) project).
]
.pull-right[
```{r ref.label='p_step_b10', echo=F, fig.width=8, fig.asp=0.618, fig.retina=3, fig.align='center'}
```
]
???
- use scales to change the default mappings of `ggplot2` afterwards
---
## 4.7 `ggplot2`: Elegant Data Visualisations
**Scales:** Scales control the aesthetic mappings by overriding the *default* settings. For example, they allow to refine the presentation of x- and y-axis, labels or color palettes ex post.
.pull-left[
**Bivariate example:**
```{r p_step_b11, eval=F}
penguins %>%
ggplot(aes(x = flipper_length_mm,
y = body_mass_g)) +
geom_point(aes(color = species),
size = 3, na.rm = TRUE) +
scale_y_log10()
```
Or use the `scale_*_log10()` functions to improve the readability of your plot in the presence of high-variance variables.
]
.pull-right[
```{r ref.label='p_step_b11', echo=F, fig.width=8, fig.asp=0.618, fig.retina=3, fig.align='center'}
```
]
???
- here it doesn't really change a lot due to the absence of outliers (respectively rahter low variations)
---
## 4.7 `ggplot2`: Elegant Data Visualisations
.pull-left[
**Other examples:** Boxplots for numeric variables
```{r, results='hide'}
penguins_long <- penguins %>%
tidyr::pivot_longer(
cols = contains("mm"),
names_to = "var", values_to = "val"
) %>%
tidyr::drop_na()
penguins_long
```
]
.pull-right[
<br>
- Use `dplyr::pivot_longer()` to bring data frame into *long* format.
- Take care of missing values using `dplyr::drop_na()` to avoid error messages.
]
```{r, echo=F}
print(penguins_long, n = 6)
```
---
## 4.7 `ggplot2`: Elegant Data Visualisations
.pull-left[
**Other examples:** Boxplots for numeric variables
```{r p_step_o1, eval=F}
penguins_long %>%
ggplot(aes(x = var, y = val)) +
geom_boxplot(na.rm = TRUE) +
geom_jitter(alpha = 0.2, width = 0.3)
```
- Use `geom_jitter()` to induce some random noise to the data points to prevent overlapping (alternative to `geom_point()`).
- Control transparency of the respective plot element via the `alpha` aesthetic.
]
.pull-right[
```{r ref.label='p_step_o1', echo=F, fig.width=8, fig.asp=0.618, fig.retina=3, fig.align='center'}
```
]
---
## 4.7 `ggplot2`: Elegant Data Visualisations
.pull-left[
**Other examples:** Ordered bar chart
```{r p_step_o2, eval=F}
plot <- penguins %>%
dplyr::count(species) %>%
dplyr::mutate(prop = n / sum(n)) %>%
ggplot()
plot +
geom_col(aes(x = prop, y = species))
```
- You can easily store an `ggplot` object in a user-defined variable.
- Use `dplyr::count()` as shortcut for `group_by()` and `summarise(n = n())`.
- You can either set `aes()` and `data` in `ggplot()` (*global*) or in `geom_*()` (*local*). In the latter case the data and mappings are only active on the *geom*-level.
]
.pull-right[
```{r ref.label='p_step_o2', echo=F, fig.width=8, fig.asp=0.618, fig.retina=3, fig.align='center'}
```
]
???
- global vs. local: if you want to use different data sets for each layer.
- see that you can easily add new layers to an preexisting `ggplot` object
---
## 4.7 `ggplot2`: Elegant Data Visualisations
.pull-left[
**Other examples:** Ordered bar chart
```{r p_step_o3, eval=F}
plot +
geom_col(
aes(x = prop,
y = forcats::fct_reorder(species, prop))) +
scale_x_continuous(
labels = scales::label_percent(1.))
```
- Use `fct_reorder()` from the `forcats` package to reorder the levels of `species` by their relative frequency (`prop`).
- Finally, `scales::label_percent(1.)` formats the axis as percentages, rounded to percentage points.
]
.pull-right[
```{r ref.label='p_step_o3', echo=F, fig.width=8, fig.asp=0.618, fig.retina=3, fig.align='center'}
```
]
---
## 4.7 `ggplot2`: Elegant Data Visualisations
.pull-left[
**Other examples:** Adjacent bar chart
```{r p_step_o4, eval=F}
penguins %>%
ggplot(aes(x = species)) +
geom_bar(aes(fill = island),
position = "dodge")
```
]
.pull-right[
```{r ref.label='p_step_o4', echo=F, fig.width=8, fig.asp=0.618, fig.retina=3, fig.align='center'}
```
]
.footnote[.pull-left[
*Note: `geom_col()` takes a `x` and `y` argument, whereas `geom_bar()` only takes an `x` argument and computes the `y`-quantity internally (e.g., the frequency using `stat = "count"`).*
]]
---
## 4.7 `ggplot2`: Elegant Data Visualisations
.pull-left[
**Other examples:** Stacked bar chart
```{r p_step_o5, eval=F}
penguins %>%
ggplot(aes(x = species)) +
geom_bar(aes(fill = island),
position = "stack")
```
]
.pull-right[
```{r ref.label='p_step_o5', echo=F, fig.width=8, fig.asp=0.618, fig.retina=3, fig.align='center'}
```
]
---
## 4.7 `ggplot2`: Elegant Data Visualisations
.pull-left[
**Other examples:** Stacked bar chart
```{r p_step_o6, eval=F}
penguins %>%
ggplot(
aes(x = forcats::fct_lump(species, n = 1))) +
geom_bar(
aes(fill = island),
position = "stack")
```
In this crude example we lump together all factor levels except the `n = 1` level(s) with the highest number of observations using `forcats::fct_lump()`.
]
.pull-right[
```{r ref.label='p_step_o6', echo=F, fig.width=8, fig.asp=0.618, fig.retina=3, fig.align='center'}
```
]
---
## 4.7 `ggplot2`: Elegant Data Visualisations
.pull-left[
**Other examples:** High-quality density plot
```{r p_step_o7, eval=F}
p <- penguins %>%
ggplot(aes(x = body_mass_g)) +
geom_density(aes(fill = species),
na.rm = T, alpha = 0.4)
p
```
]
.pull-right[
```{r ref.label='p_step_o7', echo=F, fig.width=8, fig.asp=0.618, fig.retina=3, fig.align='center'}
```
]
---
## 4.7 `ggplot2`: Elegant Data Visualisations
.pull-left[
**Other examples:** High-quality density plot
```{r p_step_o8, eval=F}
breaks <- seq(from = 3000, to = 6000, by = 500)
scales <- scales::label_comma(accuracy = 0.0001)
p <- p +
scale_x_continuous(breaks = breaks,
limits = c(2000, 7000)) +
scale_y_continuous(labels = scales)
p
```
]
.pull-right[
```{r ref.label='p_step_o8', echo=F, fig.width=8, fig.asp=0.618, fig.retina=3, fig.align='center'}
```
]
---
## 4.7 `ggplot2`: Elegant Data Visualisations
.pull-left[
**Other examples:** High-quality density plot
```{r p_step_o9, eval=F}
p <- p +
labs(
title =
"Density Function for Three Penguin Species of Palmer Penguins",
subtitle =
"Palmer Archipelago (2007-2009)",
caption =
"Data: https://github.com/allisonhorst/palmerpenguins",
x = "Body mass [grams]",
y = "Statistical density"
)
p
```
]
.pull-right[
```{r ref.label='p_step_o9', echo=F, fig.width=8, fig.asp=0.618, fig.retina=3, fig.align='center'}
```
]
---
## 4.7 `ggplot2`: Elegant Data Visualisations
.pull-left[
**Other examples:** High-quality density plot
```{r p_step_o10, eval=F}
p <- p +
theme_classic() # otherwise: theme_minimal()
p
```
The `theme` function allows you to customize all elements of your plot which are not immediately related to your data, e.g., titles, labels, fonts, background, or legends.
`ggplot2` also comes with a set of [predefined themes](https://ggplot2.tidyverse.org/reference/ggtheme.html) (`theme_*()`).
]
.pull-right[
```{r ref.label='p_step_o10', echo=F, fig.width=8, fig.asp=0.618, fig.retina=3, fig.align='center'}
```
]
---
## 4.7 `ggplot2`: Elegant Data Visualisations
.pull-left[
**Other examples:** High-quality density plot
```{r p_step_o11, eval=F, out.width='70%', fig.retina=3, fig.align='center'}
p <- p +
theme(
legend.position = "top",
plot.title =
element_text(size = 14, face = "bold"),
plot.subtitle =
element_text(size = 12),
plot.caption =
element_text(size = 10, face = "italic"),
axis.text.x =
element_text(size = 10),
axis.text.y =
element_blank(),
axis.title =
element_text(size = 10),
)
p
```
]
.pull-right[
```{r ref.label='p_step_o11', echo=F, fig.width=8, fig.asp=0.618, fig.retina=3, fig.align='center'}
```
]
---
## 4.7 `ggplot2`: Elegant Data Visualisations
.pull-left[
**Other examples:** Violin Plot
```{r p_step_o12, eval=F}
penguins %>%
ggplot(aes(x = species, y = body_mass_g)) +
geom_violin(aes(fill = species), na.rm = T) +
theme_classic()
ggsave("./img/violin-plot.PNG",
device = "png", dpi = 300)
```
- `geom_violin()` creates a cross-over version of a box-plot and a density plot, particularly suitable for visualizing continuous variables.
- `ggsave()` writes the most recent plot to disk.
]
.pull-right[
```{r ref.label='p_step_o12', echo=F, fig.width=8, fig.asp=0.618, fig.retina=3, fig.align='center', message=F}
```
]
---
## 4.7 `ggplot2`: Elegant Data Visualisations
.pull-left[
**Other examples:** Lines of Best Fit
```{r p_step_b13, eval=F}
penguins %>%
tidyr::drop_na() %>%
ggplot(aes(x = flipper_length_mm,
y = body_mass_g)) +
geom_point(aes(color = species)) +
geom_smooth(method = "lm", se = T)
```
- Use `geom_smooth()` to fit a smooth line to depict the relationship between `x` and `y`.
- For the `method` argument specify one of:
- *lm* (linear model),
- *glm* (generalized linear model),
- *gam* (generalized additive model),
- *loess* (local regression).
- Set the `se` argument to `TRUE` to obtain standard error bands (i.e. confidence intervals).
]
.pull-right[
.panelset[
.panel[.panel-name[lm]
```{r, echo=F, fig.width=8, fig.asp=0.618, fig.retina=3, fig.align='center', message=F}
penguins %>%
tidyr::drop_na() %>%
ggplot(aes(x = flipper_length_mm,
y = body_mass_g)) +
geom_point(aes(color = species)) +
geom_smooth(method = "lm", se = T)
```
]
.panel[.panel-name[glm]
```{r, echo=F, fig.width=8, fig.asp=0.618, fig.retina=3, fig.align='center', message=F}
penguins %>%
tidyr::drop_na() %>%
ggplot(aes(x = flipper_length_mm,
y = body_mass_g)) +
geom_point(aes(color = species)) +
geom_smooth(method = "glm", se = T)
```
]
.panel[.panel-name[gam]
```{r, echo=F, fig.width=8, fig.asp=0.618, fig.retina=3, fig.align='center', message=F}
penguins %>%
tidyr::drop_na() %>%
ggplot(aes(x = flipper_length_mm,
y = body_mass_g)) +
geom_point(aes(color = species)) +
geom_smooth(method = "gam", se = T)
```
]
.panel[.panel-name[loess]
```{r, echo=F, fig.width=8, fig.asp=0.618, fig.retina=3, fig.align='center', message=F}
penguins %>%
tidyr::drop_na() %>%
ggplot(aes(x = flipper_length_mm,
y = body_mass_g)) +
geom_point(aes(color = species)) +
geom_smooth(method = "loess", se = T)
```
]
]
]
???
- lm: y follows the normal distribution
- glm: y follows distribution other than normal (e.g., logistic or poisson), but also includes lm (generalization)
- gam: y and x can be exhibit non-linear relationships
- loess: local regression fits the relationship between y and x locally and allows for substantial non-linearities
---
## 4.7 `ggplot2`: Elegant Data Visualisations
By now, there is a whole ecosystem (aka the [ggverse](https://github.com/erikgahner/awesome-ggplot2)) of amazing packages, all created in the spirit of `ggplot2`, which further extend its capabilities:
```{r, echo=F, out.height='40%', out.width='40%', dpi=100, out.extra='style="float:right; padding:10px"'}
knitr::include_graphics(
"https://tenor.com/view/shocked-po-kung-fu-panda-gif-4255877.gif"
)
```
- `scales`: Scale Functions for Visualization
- `ggtext`: Improved Text Rendering Support for `ggplot2`
- `ggraph`: An Implementation of Grammar of Graphics for Graphs and Networks
- `ggstatsplot`: `ggplot2` Based Plots with Statistical Details
- `plotly`: Create Interactive Web Graphics via `plotly.js`
- `patchwork`: The Composer of Plots
- `ggforce`: Accelerating `ggplot2`
- etc.
???
- ggforce: extension off ggplot2 functionality to allows for more customizations
---
background-image: url(https://raw.githubusercontent.com/ropensci/plotly/master/man/figures/plotly.png)
background-position: 97.5% 2.5%
background-size: 15%
layout: false
## 4.7 `plotly`: Interactive Web Graphics
```{r, out.height='70%', out.width='100%'}
plotly::ggplotly(p)
```
---
background-image: url(https://raw.githubusercontent.com/thomasp85/patchwork/master/man/figures/logo.png)
background-position: 97.5% 2.5%
background-size: 7.5%
layout: false
## 4.7 `patchwork`: The Composer of Plots
.pull-left[
```{r, fig.width=8, fig.asp=0.618, fig.retina=3, fig.align='center'}
library(patchwork)
p + p + p
```
]
.pull-right[
```{r, fig.width=8, fig.asp=0.618, fig.retina=3, fig.align='center'}
library(patchwork)
p + (p / p)
```
]
---
background-image: url(https://raw.githubusercontent.com/thomasp85/ggforce/master/man/figures/logo.png)
background-position: 97.5% 2.5%
background-size: 7.5%
layout: false
## 4.7 `ggforce`: Accelerating `ggplot2`
.pull-left[
```{r ggforce, eval=F}
penguins %>%
drop_na %>%
ggplot(aes(x = .panel_x,
y = .panel_y,
col = sex,
fill = sex)) +
ggforce::geom_autopoint(alpha = 0.5) +
ggforce::geom_autohistogram(alpha = 0.5) +
ggforce::facet_matrix(
rows = vars(species, island,
body_mass_g,
flipper_length_mm),
switch = "both", layer.diag = 2) +
theme_bw() +
theme(axis.text.x = element_text(angle = 90))
```
]
.pull-right[
```{r ref.label='ggforce', echo=F, fig.width=8, fig.asp=0.618, fig.retina=3, fig.align='center'}
```
]