-
Notifications
You must be signed in to change notification settings - Fork 253
/
exercises.Rmd
880 lines (717 loc) · 23.9 KB
/
exercises.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
---
title: "ggplot2 examples and exercises"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
This document contains all the code that is displayed during the workshop. The
document is an RMarkdown document which means that it can be compiled, along
with the code chunks thus executing and capturing the output of the code within
the document. To read more about RMarkdown see the website for the package, as
well as the [Get Started](https://rmarkdown.rstudio.com/lesson-1.html) guide.
### Exercises
While it is encouraged to follow along in this document as the workshop
progresses and execute the code to see the result, an important part is also to
experiment and play, thus learning how the different settings affect the output.
The document will contain code chunks with the code examples discussed during
the talk, but it will also contain chunks intended for completing small
exercises. These will use the examples as a starting point and ask you to modify
the code to achieve a given output. Completing these are optional, but highly
recommended, either during or after the workshop.
### Dependencies
This document comes with a list of required packages.
```{r, echo=FALSE}
packages <- c(
'ggplot2',
'ggrepel',
'patchwork',
'ggraph',
'dplyr',
'gganimate',
'gifski',
'ggforce',
'ggthemes',
'maps',
'sf',
'tidyr',
'concaveman',
'remotes'
)
# Uncomment the next lines (remove the first #) to install the packages
# install.packages(packages)
# remotes::install_github("hrbrmstr/hrbrthemes")
# Load standard packages
library(ggplot2)
```
### Datasets
We will use an assortment of datasets throughout the document. The purpose is
mostly to showcase different plots, and less on getting some divine insight into
the world. While not necessary we will call `data(<dataset>)` before using a new
dataset to indicate the introduction of a new dataset.
## Introduction
We will look at the basic ggplot2 use using the faithful dataset, giving
information on the eruption pattern of the Old Faithful geyser in Yellowstone
National Park.
```{r}
data("faithful")
# Basic scatterplot
ggplot(data = faithful,
mapping = aes(x = eruptions, y = waiting)) +
geom_point()
# Data and mapping can be given both as global (in ggplot()) or per layer
ggplot() +
geom_point(mapping = aes(x = eruptions, y = waiting),
data = faithful)
```
If an aesthetic is linked to data it is put into `aes()`
```{r}
ggplot(faithful) +
geom_point(aes(x = eruptions, y = waiting, colour = eruptions < 3))
```
If you simple want to set it to a value, put it outside of `aes()`
```{r}
ggplot(faithful) +
geom_point(aes(x = eruptions, y = waiting),
colour = 'steelblue')
```
Some geoms only need a single mapping and will calculate the rest for you
```{r}
ggplot(faithful) +
geom_histogram(aes(x = eruptions))
```
geoms are drawn in the order they are added. The point layer is thus drawn on
top of the density contours in the example below.
```{r}
ggplot(faithful, aes(x = eruptions, y = waiting)) +
geom_density_2d() +
geom_point()
```
#### Exercise
Modify the code below to make the points larger squares and slightly transparent.
See `?geom_point` for more information on the point layer.
```{r}
ggplot(faithful) +
geom_point(aes(x = eruptions, y = waiting))
```
Hint 1: transparency is controlled with `alpha`, and shape with `shape`
Hint 2: rememberthe difference between mapping and setting aesthetics
* * *
Colour the two distributions in the histogram with different colours
```{r}
ggplot(faithful) +
geom_histogram(aes(x = eruptions))
```
Hint 1: For polygons you can map two different colour-like aesthetics: `colour`
(the colour of the stroke) and `fill` (the fill colour)
* * *
Colour the distributions in the histogram by whether `waiting` is above or below
`60`. What happens?
```{r}
ggplot(faithful) +
geom_histogram(aes(x = eruptions))
```
Change the plot above by setting `position = 'dodge'` in `geom_histogram()`
(while keeping the colouring by `waiting`). What do `position` control?
* * *
Add a line that separates the two point distributions. See `?geom_abline` for
how to draw straight lines from a slope and intercept.
```{r}
ggplot(faithful) +
geom_point(aes(x = eruptions, y = waiting))
```
### Stat
We will use the `mpg` dataset giving information about fuel economy on different
car models.
Every geom has a stat. This is why new data (`count`) can appear when using
`geom_bar()`.
```{r}
data("mpg")
ggplot(mpg) +
geom_bar(aes(x = class))
```
The stat can be overwritten. If we have precomputed count we don't want any
additional computations to perform and we use the `identity` stat to leave the
data alone
```{r}
library(dplyr)
mpg_counted <- mpg %>%
count(class, name = 'count')
ggplot(mpg_counted) +
geom_bar(aes(x = class, y = count), stat = 'identity')
```
Most obvious geom+stat combinations have a dedicated geom constructor. The one
above is available directly as `geom_col()`
```{r}
ggplot(mpg_counted) +
geom_col(aes(x = class, y = count))
```
Values calculated by the stat is available with the `after_stat()` function
inside `aes()`. You can do all sorts of computations inside that.
```{r}
ggplot(mpg) +
geom_bar(aes(x = class, y = after_stat(100 * count / sum(count))))
```
Many stats provide multiple variations of the same calculation, and provides a
default (here, `density`)
```{r}
ggplot(mpg) +
geom_density(aes(x = hwy))
```
While the others must be used with the `after_stat()` function
```{r}
ggplot(mpg) +
geom_density(aes(x = hwy, y = after_stat(scaled)))
```
#### Exercises
While most people use `geom_*()` when adding layers, it is just as valid to add
a `stat_*()` with an attached geom. Look at `geom_bar()` and figure out which
stat it uses as default. Then modify the code to use the stat directly instead
(i.e. adding `stat_*()` instead of `geom_bar()`)
```{r}
ggplot(mpg) +
geom_bar(aes(x = class))
```
* * *
Use `stat_summary()` to add a red dot at the mean `hwy` for each group
```{r}
ggplot(mpg) +
geom_jitter(aes(x = class, y = hwy), width = 0.2)
```
Hint: You will need to change the default geom of `stat_summary()`
### Scales
Scales define how the mapping you specify inside `aes()` should happen. All
mappings have an associated scale even if not specified.
```{r}
ggplot(mpg) +
geom_point(aes(x = displ, y = hwy, colour = class))
```
take control by adding one explicitly. All scales follow the same naming
conventions.
```{r}
ggplot(mpg) +
geom_point(aes(x = displ, y = hwy, colour = class)) +
scale_colour_brewer(type = 'qual')
```
Positional mappings (x and y) also have associated scales.
```{r}
ggplot(mpg) +
geom_point(aes(x = displ, y = hwy)) +
scale_x_continuous(breaks = c(3, 5, 6)) +
scale_y_continuous(trans = 'log10')
```
#### Exercises
Use `RColorBrewer::display.brewer.all()` to see all the different palettes from
Color Brewer and pick your favourite. Modify the code below to use it
```{r}
ggplot(mpg) +
geom_point(aes(x = displ, y = hwy, colour = class)) +
scale_colour_brewer(type = 'qual')
```
* * *
Modify the code below to create a bubble chart (scatterplot with size mapped to
a continuous variable) showing `cyl` with size. Make sure that only the present
amount of cylinders (4, 5, 6, and 8) are present in the legend.
```{r}
ggplot(mpg) +
geom_point(aes(x = displ, y = hwy, colour = class)) +
scale_colour_brewer(type = 'qual')
```
Hint: The `breaks` argument in the scale is used to control which values are
present in the legend.
Explore the different types of size scales available in ggplot2. Is the default
the most appropriate here?
* * *
Modify the code below so that colour is no longer mapped to the discrete `class`
variable, but to the continuous `cty` variable. What happens to the guide?
```{r}
ggplot(mpg) +
geom_point(aes(x = displ, y = hwy, colour = class, size = cty))
```
* * *
The type of guide can be controlled with the `guide` argument in the scale, or
with the `guides()` function. Continuous colours have a gradient colour bar by
default, but setting it to `legend` will turn it back to the standard look. What
happens when multiple aesthetics are mapped to the same variable and uses the
guide type?
```{r}
ggplot(mpg) +
geom_point(aes(x = displ, y = hwy, colour = cty, size = cty))
```
### Facets
The facet defines how data is split among panels. The default facet
(`facet_null()`) puts all the data in a single panel, while `facet_wrap()` and
`facet_grid()` allows you to specify different types of small multiples
```{r}
ggplot(mpg) +
geom_point(aes(x = displ, y = hwy)) +
facet_wrap(~ class)
```
```{r}
ggplot(mpg) +
geom_point(aes(x = displ, y = hwy)) +
facet_grid(year ~ drv)
```
#### Exercises
One of the great things about facets is that they share the axes between the
different panels. Sometimes this is undiserable though, and the behaviour can
be changed with the `scales` argument. Experiment with the different possible
settings in the plot below:
```{r}
ggplot(mpg) +
geom_point(aes(x = displ, y = hwy)) +
facet_wrap(~ drv)
```
* * *
Usually the space occupied by each panel is equal. This can create problems when
different scales are used. Modify the code below so that the y scale differs
between the panels in the plot. What happens?
```{r}
ggplot(mpg) +
geom_bar(aes(y = manufacturer)) +
facet_grid(class ~ .)
```
Use the `space` argument in `facet_grid()` to change the plot above so each bar
has the same width again.
* * *
Facets can be based on multiple variables by adding them together. Try to
recreate the same panels present in the plot below by using `facet_wrap()`
```{r}
ggplot(mpg) +
geom_point(aes(x = displ, y = hwy)) +
facet_grid(year ~ drv)
```
### Coordinates
The coordinate system is the fabric you draw your layers on in the end. The
default `coord_cartesion provides the standard rectangular x-y coordinate
system. Changing the coordinate system can have dramatic effects
```{r}
ggplot(mpg) +
geom_bar(aes(x = class)) +
coord_polar()
```
```{r}
ggplot(mpg) +
geom_bar(aes(x = class)) +
coord_polar(theta = 'y') +
expand_limits(y = 70)
```
You can zoom both on the scale...
```{r}
ggplot(mpg) +
geom_bar(aes(x = class)) +
scale_y_continuous(limits = c(0, 40))
```
and in the coord. You usually want the latter as it avoids changing the plottet
data
```{r}
ggplot(mpg) +
geom_bar(aes(x = class)) +
coord_cartesian(ylim = c(0, 40))
```
#### Exercises
In the same way as limits can be set in both the positional scale and the coord,
so can transformations, using `coord_trans()`. Modify the code below to apply a
log transformation to the y axis; first using `scale_y_continuous()`,
and then using `coord_trans()`. Compare the results — how do they differ?
```{r}
ggplot(mpg) +
geom_point(aes(x = hwy, y = displ))
```
* * *
Coordinate systems are particularly important in cartography. While we will not
spend a lot of time with it in this workshop, spatial plotting is well supported
in ggplot2 with `geom_sf()` and `coord_sf()` (which interfaces with the sf
package). The code below produces a world map. Try changing the `crs` argument
in `coord_sf()` to be `'+proj=robin'` (This means using the Robinson projection).
```{r}
# Get the borders of all countries
world <- sf::st_as_sf(maps::map('world', plot = FALSE, fill = TRUE))
world <- sf::st_wrap_dateline(world,
options = c("WRAPDATELINE=YES", "DATELINEOFFSET=180"),
quiet = TRUE)
# Plot code
ggplot(world) +
geom_sf() +
coord_sf(crs = "+proj=moll")
```
Maps are a huge area in data visualisation and simply too big to cover in this
workshop. If you want to explore further I advice you to explore the
[r-spatial wbsite](https://www.r-spatial.org) as well as the website for the
[sf package](https://r-spatial.github.io/sf)
### Theme
Theming defines the feel and look of your final visualisation and is something
you will normally defer to the final polishing of the plot. It is very easy to
change looks with a prebuild theme
```{r}
ggplot(mpg) +
geom_bar(aes(y = class)) +
facet_wrap(~year) +
theme_minimal()
```
Further adjustments can be done in the end to get exactly the look you want
```{r}
ggplot(mpg) +
geom_bar(aes(y = class)) +
facet_wrap(~year) +
labs(title = "Number of car models per class",
caption = "source: http://fueleconomy.gov",
x = NULL,
y = NULL) +
scale_x_continuous(expand = c(0, NA)) +
theme_minimal() +
theme(
text = element_text('Avenir Next Condensed'),
strip.text = element_text(face = 'bold', hjust = 0),
plot.caption = element_text(face = 'italic'),
panel.grid.major = element_line('white', size = 0.5),
panel.grid.minor = element_blank(),
panel.grid.major.y = element_blank(),
panel.ontop = TRUE
)
```
#### Exercises
Themes can be overwhelming, especially as you often try to optimise for beauty
while you learn. To remove the last part of the equation, the exercise is to
take the plot given below and make it as hideous as possible using the theme
function. Go absolutely crazy, but take note of the effect as you change
different settings.
```{r}
ggplot(mpg) +
geom_bar(aes(y = class, fill = drv)) +
facet_wrap(~year) +
labs(title = "Number of car models per class",
caption = "source: http://fueleconomy.gov",
x = 'Number of cars',
y = NULL)
```
## Extensions
While ggplot2 comes with a lot of batteries included, the extension ecosystem
provides priceless additinal features
### Plot composition
We start by creating 3 separate plots
```{r}
p1 <- ggplot(msleep) +
geom_boxplot(aes(x = sleep_total, y = vore, fill = vore))
p1
```
```{r}
p2 <- ggplot(msleep) +
geom_bar(aes(y = vore, fill = vore))
p2
```
```{r}
p3 <- ggplot(msleep) +
geom_point(aes(x = bodywt, y = sleep_total, colour = vore)) +
scale_x_log10()
p3
```
Combining them with patchwork is a breeze using the different operators
```{r}
library(patchwork)
p1 + p2 + p3
(p1 | p2) /
p3
p_all <- (p1 | p2) /
p3
p_all + plot_layout(guides = 'collect')
p_all & theme(legend.position = 'none')
p_all <- p_all & theme(legend.position = 'none')
p_all + plot_annotation(
title = 'Mammalian sleep patterns',
tag_levels = 'A'
)
```
#### Excercises
Patchwork will assign the same amount of space to each plot by default, but this
can be controlled with the `widths` and `heights` argument in `plot_layout()`.
This can take a numeric vector giving their relative sizes (e.g. `c(2, 1)` will
make the first plot twice as big as the second). Modify the code below so that
the middle plot takes up half of the total space:
```{r}
p <- ggplot(mtcars) +
geom_point(aes(x = disp, y = mpg))
p + p + p
```
* * *
The `&` operator can be used with any type of ggplot2 object, not just themes.
Modify the code below so the two plots share the same y-axis (same limits)
```{r}
p1 <- ggplot(mtcars[mtcars$gear == 3,]) +
geom_point(aes(x = disp, y = mpg))
p2 <- ggplot(mtcars[mtcars$gear == 4,]) +
geom_point(aes(x = disp, y = mpg))
p1 + p2
```
* * *
Patchwork contains many features for fine tuning the layout and annotation. Very
complex layouts can be obtained by providing a design specification to the
`design` argument in `plot_layout()`. The design can be defined as a textual
representation of the cells. Use the layout given below. How should the textual
representation be undertood.
```{r}
p1 <- ggplot(mtcars) +
geom_point(aes(x = disp, y = mpg))
p2 <- ggplot(mtcars) +
geom_bar(aes(x = factor(gear)))
p3 <- ggplot(mtcars) +
geom_boxplot(aes(x = factor(gear), y = mpg))
layout <- '
AA#
#BB
C##
'
p1 + p2 + p3 + plot_layout(design = layout)
```
### Animation
ggplot2 is usually focused on static plots, but gganimate extends the API and
grammar to describe animations. As such it feels like a very natural extension
of using ggplot2
```{r}
ggplot(economics) +
geom_line(aes(x = date, y = unemploy))
library(gganimate)
ggplot(economics) +
geom_line(aes(x = date, y = unemploy)) +
transition_reveal(along = date)
```
There are many different transitions that control how data is interpreted for
animation, as well as a range of other animation specific features
```{r}
ggplot(mpg) +
geom_bar(aes(x = factor(cyl)))
ggplot(mpg) +
geom_bar(aes(x = factor(cyl))) +
labs(title = 'Number of cars in {closest_state} by number of cylinders') +
transition_states(states = year) +
enter_grow() +
exit_fade()
```
#### Exercises
The animation below will animate between points showing cars with different
cylinders.
```{r}
ggplot(mpg) +
geom_point(aes(x = displ, y = hwy)) +
ggtitle("Cars with {closest_state} cylinders") +
transition_states(factor(cyl))
```
gganimate uses the `group` aesthetic to match observations between states. By
default the group aesthetic is set to the same value, so observations are
matched by their position (first row of 4 cyl is matched to first row of 5 cyl
etc.). This is clearly wrong here (why?). Add a mapping to the `group` aesthetic
to ensure that points do not move between the different states.
* * *
In the presence of discrete aesthetic mappings (`colour` below), the group is
deduced if not given. The default behaviour of objects that appear and disappear
during the animation is to simply pop in and out of existance. `enter_*()` and
`exit_*()` functions can be used to control this behaviour. Experiment with the
different enter and exit functions provided by gganimate below. What happens if
you add multiple enter or exit functions to the same animation?
```{r}
ggplot(mpg) +
geom_point(aes(x = displ, y = hwy, colour = factor(cyl))) +
ggtitle("Cars with {closest_state} cylinders") +
transition_states(factor(cyl))
```
* * *
In the animation below (as in all the other animations) the changes happens at
constant speed. How values change during an animation is called easing and can
be controlled using the `ease_aes()` function. Read the documentation for
`ease_aes()` and experiment with different easings in the animation.
```{r}
mpg2 <- tidyr::pivot_longer(mpg, c(cty,hwy))
ggplot(mpg2) +
geom_point(aes(x = displ, y = value)) +
ggtitle("{if (closest_state == 'cty') 'Efficiency in city' else 'Efficiency on highway'}") +
transition_states(name)
```
### Annotation
Text is a huge part of storytelling with your visualisation. Historically,
textual annotations has not been the best part of ggplot2 but new extensions
make up for that.
Standard geom_text will often result in overlaping labels
```{r}
ggplot(mtcars, aes(x = disp, y = mpg)) +
geom_point() +
geom_text(aes(label = row.names(mtcars)))
```
ggrepel takes care of that
```{r}
library(ggrepel)
ggplot(mtcars, aes(x = disp, y = mpg)) +
geom_point() +
geom_text_repel(aes(label = row.names(mtcars)))
```
If you want to highlight certain parts of your data and describe it, the
`geom_mark_*()` family of geoms have your back
```{r}
library(ggforce)
ggplot(mtcars, aes(x = disp, y = mpg)) +
geom_point() +
geom_mark_ellipse(aes(filter = gear == 4,
label = '4 gear cars',
description = 'Cars with fewer gears tend to both have higher yield and lower displacement'))
```
#### Exercises
ggrepel has a tonne of settings for controlling how text labels move. Often,
though, the most effective is simply to not label everything. There are two
strategies for that: Either only use a subset of the data for the repel layer,
or setting the label to `""` for those you don't want to plot. Try both in the
plot below where you only label 10 random points.
```{r}
mtcars2 <- mtcars
mtcars2$label <- rownames(mtcars2)
points_to_label <- sample(nrow(mtcars), 10)
ggplot(mtcars2, aes(x = disp, y = mpg)) +
geom_point() +
geom_text_repel(aes(label = label))
```
* * *
Explore the documentation for `geom_text_repel`. Find a way to ensure that the
labels in the plot below only repels in the vertical direction
```{r}
mtcars2$label <- ""
mtcars2$label[1:10] <- rownames(mtcars2)[1:10]
ggplot(mtcars2, aes(x = disp, y = mpg)) +
geom_point() +
geom_text_repel(aes(label = label))
```
* * *
ggforce comes with 4 different types of mark geoms. Try them all out in the code
below:
```{r}
ggplot(mtcars, aes(x = disp, y = mpg)) +
geom_point() +
geom_mark_ellipse(aes(filter = gear == 4,
label = '4 gear cars'))
```
### Networks
ggplot2 has been focused on tabular data. Network data in any shape and form is
handled by ggraph
```{r}
library(ggraph)
library(tidygraph)
graph <- create_notable('zachary') %>%
mutate(clique = as.factor(group_infomap()))
ggraph(graph) +
geom_mark_hull(aes(x, y, fill = clique)) +
geom_edge_link() +
geom_node_point(size = 2)
```
dendrograms are just a specific type of network
```{r}
iris_clust <- hclust(dist(iris[, 1:4]))
ggraph(iris_clust) +
geom_edge_bend() +
geom_node_point(aes(filter = leaf))
```
#### Exercies
Most network plots are defined by a layout algorithm, which takes the network
structure and calculate a position for each node. The layout algorithm is
global and set in the `ggraph()`. The default `auto` layout will inspect the
network object and try to choose a sensible layout for it (e.g. dendrogram for a
hierarchical clustering as above). There is, however no optimal layout and it is
often a good idea to try out different layouts. Try out different layouts in the
graph below. See the [the website](https://ggraph.data-imaginist.com/reference/index.html)
for an overview of the different layouts.
```{r}
ggraph(graph) +
geom_edge_link() +
geom_node_point(aes(colour = clique), size = 3)
```
* * *
There are many different ways to draw edges. Try to use `geom_edge_parallel()`
in the graph below to show the presence of multiple edges
```{r}
highschool_gr <- as_tbl_graph(highschool)
ggraph(highschool_gr) +
geom_edge_link() +
geom_node_point()
```
Faceting works in ggraph as it does in ggplot2, but you must choose to facet by
either nodes or edges. Modify the graph below to facet the edges by the `year`
variable (using `facet_edges()`)
```{r}
ggraph(highschool_gr) +
geom_edge_fan() +
geom_node_point()
```
### Looks
Many people have already desgned beautiful (and horrible) themes for you. Use
them as a base
```{r}
p <- ggplot(mtcars, aes(mpg, wt)) +
geom_point(aes(color = factor(carb))) +
labs(
x = 'Fuel efficiency (mpg)',
y = 'Weight (tons)',
title = 'Seminal ggplot2 example',
subtitle = 'A plot to show off different themes',
caption = 'Source: It’s mtcars — everyone uses it'
)
library(hrbrthemes)
p +
scale_colour_ipsum() +
theme_ipsum()
```
```{r}
library(ggthemes)
p +
scale_colour_excel() +
theme_excel()
```
## Drawing anything
```{r}
states <- c(
'eaten', "eaten but said you didn\'t", 'cat took it', 'for tonight',
'will decompose slowly'
)
pie <- data.frame(
state = factor(states, levels = states),
amount = c(4, 3, 1, 1.5, 6),
stringsAsFactors = FALSE
)
ggplot(pie) +
geom_col(aes(x = 0, y = amount, fill = state))
```
```{r}
ggplot(pie) +
geom_col(aes(x = 0, y = amount, fill = state)) +
coord_polar(theta = 'y')
```
```{r}
ggplot(pie) +
geom_col(aes(x = 0, y = amount, fill = state)) +
coord_polar(theta = 'y') +
scale_fill_tableau(name = NULL,
guide = guide_legend(ncol = 2)) +
theme_void() +
theme(legend.position = 'top',
legend.justification = 'left')
```
```{r}
ggplot(pie) +
geom_arc_bar(aes(x0 = 0, y0 = 0, r0 = 0, r = 1, amount = amount, fill = state), stat = 'pie') +
coord_fixed()
```
```{r}
ggplot(pie) +
geom_arc_bar(aes(x0 = 0, y0 = 0, r0 = 0, r = 1, amount = amount, fill = state), stat = 'pie') +
coord_fixed() +
scale_fill_tableau(name = NULL,
guide = guide_legend(ncol = 2)) +
theme_void() +
theme(legend.position = 'top',
legend.justification = 'left')
```
```{r}
ggplot(mpg) +
# geom_bar(aes(x = hwy), stat = 'bin')
geom_histogram(aes(x = hwy))
```
```{r}
ggplot(mpg) +
geom_bar(aes(x = hwy)) +
scale_x_binned(n.breaks = 30, guide = guide_axis(n.dodge = 2))
```