-
Notifications
You must be signed in to change notification settings - Fork 14
/
index.qmd
957 lines (768 loc) · 30.7 KB
/
index.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
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
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
---
title: "The untold story of palmerpenguins 🐧"
author:
- Dr. Kristen Gorman, University of Alaska Fairbanks
- Dr. Allison Horst, UC Santa Barbara
- Dr. Alison Hill, Voltron Data
format:
revealjs:
multiplex: true
footer: "[apreshill.github.io/palmerpenguins-useR-2022/](https://apreshill.github.io/palmerpenguins-useR-2022/)"
theme: ["pp.scss"]
slide-number: c/t
incremental: true
title-slide-attributes:
data-background-image: img/penguin-highway.jpg
data-background-size: cover
editor: visual
---
```{r setup}
#| include: false
library(palmerpenguins)
# for interactive plots
library(ggiraph)
library(patchwork)
library(shadowtext)
# for color
library(paletteer)
# for cran plots
library(cranlogs)
library(tidyverse)
library(scales)
# for fonts
library(showtext)
font_add_google("Jost", "Jost")
showtext_auto()
theme_set(theme_minimal(base_family = "Jost"))
library(recipes)
library(broom)
# for reporting cran downloads
start_date <- "2020-07-23"
end_date <- "2022-06-15"
```
```{r}
#| eval: false
#| include: false
# do this just once
dl <- cranlogs::cran_downloads("palmerpenguins",
from = start_date,
to = end_date) %>%
as_tibble()
saveRDS(dl, file = "data/cran-downloads.RDS")
```
## What is palmerpenguins?
::: columns
::: column
- An R package featuring the `penguins` dataset
- `r nrow(penguins)` penguins
- `r n_distinct(penguins$species)` penguin species (Adélie, chinstrap, and gentoo)
- `Inf` fun
:::
::: column
```{r}
#| fig.alt: "Scatterplot showing linear relationships between penguin body mass and flipper length, both across and within species (Adelie, Chinstrap and Gentoo)."
# make the base plot
penguin_linear_base <-
penguins %>%
mutate(species = as.character(species)) %>%
mutate(species = case_when(
species == "Adelie" ~ "Adélie",
TRUE ~ species
)) %>%
ggplot(aes(x = flipper_length_mm, y = body_mass_g)) +
scale_color_paletteer_d("colorblindr::OkabeIto") +
theme(legend.position = c(0.2,0.85)) +
labs(x = "Flipper length (mm)",
y = "Body mass (g)") +
theme(plot.title.position = "plot",
#panel.grid = element_blank(),
panel.border = element_rect(fill = NA, color = "gray70"),
legend.title = element_blank())
# add interactivity
penguins_tooltip <- c(str_c("Flipper length (mm) = ", penguins$flipper_length_mm,
"\n Body mass (g) = ", penguins$body_mass_g,
"\n Species = ", penguins$species))
penguin_linear_int <-
penguin_linear_base +
geom_point_interactive(aes(color = species,
shape = species,
tooltip = penguins_tooltip,
data_id = species),
size = 2,
alpha = .8
) +
geom_smooth_interactive(aes(group = species,
color = species,
data_id= species),
method = lm,
se = FALSE
)
girafe(ggobj = penguin_linear_int,
options = list(
opts_hover_inv(css = "opacity:0.2;"),
opts_hover(css = "opacity:1; filter: brightness(90%);")
))
```
:::
:::
::: notes
Kristen presents
:::
## palmerpenguins popularity
```{r}
dl <- readRDS("data/cran-downloads.RDS")
```
::: columns
::: {.column width="80%"}
```{r cran-trend}
#| fig.alt: "Line graph showing palmerpenguins package downloads from CRAN, which increases quickly since published in 2020 and has leveled off near 1000 downloads per day."
#| fig.height: 4
# from https://github.com/hadley/cran-downloads/blob/master/server.R
show_trend <- function(df) {
count_ts <- ts(df$count, frequency = 7)
stl <- tryCatch(
as.data.frame(stl(count_ts, "periodic")$time.series),
error = function(e) data.frame(trend = df$count, remainder = 0)
)
df$trend <- stl$trend
df$remainder <- stl$remainder
df
}
trend <- dl %>% group_by(package) %>% do(show_trend(.))
ggplot(trend, aes(date)) +
geom_linerange(aes(ymin = trend, ymax = trend + remainder), colour = "grey70", alpha = .5, lwd = 1) +
geom_line(aes(y = trend), color = "#FB7967", lwd = 1) +
labs(y = "Daily downloads (smoothed)", x = NULL)
```
- \> `r scales::number(sum(dl$count), big.mark = ",", accuracy = 100)` CRAN downloads since `r start_date`
- Used globally in courses, workshops, blog posts, and other learning materials
- `penguins` now in [Python](https://github.com/mcnakhaee/palmerpenguins), [Julia](https://juliahub.com/ui/Packages/PalmerPenguins/L7ZJc/0.1.4), and [TensorFlow](https://www.tensorflow.org/datasets/catalog/penguins)
:::
::: {.column width="20%"}
[![palmerpenguins hex sticker by Allison Horst](https://allisonhorst.github.io/palmerpenguins/reference/figures/palmerpenguins.png){fig-alt="palmerpenguins hex sticker with all three penguin species by Allison Horst"}](https://allisonhorst.github.io/palmerpenguins/index.html)
:::
:::
::: notes
Kristen presents
:::
## {background-image="img/penguins.png"}
### How the penguins came to be {.r-fit-text}
## The research
::: columns
::: {.column width="50%"}
![Dr. Kristen Gorman in the field, surrounded by penguins, at islands near Palmer Archipelago, Antarctica](img/kristen.png){fig-alt="Dr. Kristen Gorman in the field, surrounded by penguins, at islands near Palmer Archipelago, Antarctica"}
:::
::: {.column width="50%"}
- An integrative study of the breeding ecology and population structure of Pygoscelis penguins along the western Antarctic Peninsula as part of the Palmer LTER Program (US NSF)
- The data were [originally published](https://doi.org/10.1371/journal.pone.0090081) in PLoS ONE in 2014[^1]
- All data were made available through the [Environmental Data Initiative](https://environmentaldatainitiative.org)
:::
:::
[^1]: Gorman KB, Williams TD, Fraser WR (2014). Ecological sexual dimorphism and environmental variability within a community of Antarctic penguins (genus Pygoscelis). PLoS ONE 9(3):e90081. <https://doi.org/10.1371/journal.pone.0090081>
::: notes
Kristen presents
:::
## {background-image="img/avian-island.jpeg"}
### Little did the penguin research team know... {.r-fit-text}
## Wanted: an alternative to iris
::: columns
::: column
[![Measurements of an iris flower (source: Science Direct)](img/iris.jpeg){fig-alt="Measurements of an iris flower"}](https://www.sciencedirect.com/topics/mathematics/virginica)
:::
::: column
- Collected by botanist Edgar Anderson in 1935
- Used *everywhere* in data science teaching & resources
- `r nrow(iris)` size measurements for `r n_distinct(iris$Species)` species of iris
- No missing values
- Lacks metadata
- Variables like `Sepal.Width`
- Published in The Annals of Eugenics (RA Fisher, 1936)
:::
:::
::: notes
Allison presents
:::
## If something is a problem, offer a solution
1. Keep using `iris` and use it as an opportunity to learn/teach about its problematic aspects.
2. Find a better dataset to replace `iris`.
## {background-image="img/penguin.jpeg"}
### The eternal search for (better) useful datasets for teaching {.r-fit-text}
## Serendipity
::: columns
::: {.column width="60%"}
- Allison stumbles upon [Gorman et al.](https://dx.plos.org/10.1371/journal.pone.0090081) and shares it with Alison
- Alison writes a [blog post](https://www.apreshill.com/blog/2020-02-take-a-sad-script-make-it-better-tidymodels-edition/) with penguins after Allison shares it with her
[![Screenshot from Alison's first blog post using penguins from Allison](img/blog-post.png)](https://www.apreshill.com/blog/2020-02-take-a-sad-script-make-it-better-tidymodels-edition/)
:::
::: {.column width="40%"}
[![Art by Rohan Chakravarty](https://www.apreshill.com/blog/2020-02-take-a-sad-script-make-it-better-tidymodels-edition/penguins-of-the-world.JPG){fig-alt="21 of the described species with their respective IUCN status. Aquatic and flightless birds with remarkable swimming adaptations, penguins inhabit the Southern hemisphere (except the Galapagos Penguin). They range in size from the 45 kg Emperor Penguin to the 1.5 kg Little Penguin. Penguins are threatened by habitat loss and climate change, and the African, Galapagos and Yellow-eyed are some of the most endangered penguin species." width="80%"}](https://www.greenhumour.com/2018/04/penguins-of-world.html)
:::
:::
::: notes
Allison presents
:::
## Finding the one
::: columns
::: column
- Meanwhile, Allison keeps playing with the penguins
- And plotting with the penguins
- And looking at more penguin pictures
- Aligns eerily well with iris data
:::
::: column
```{r}
#| fig.alt: "Scatterplots highlighting linear relationships between penguin body mass and flipper length (left) and iris petal length and petal width (right), both across and within the three species for each dataset."
# Iris linear relationships (petal dimensions):
iris_linear_base <- ggplot(iris, aes(x = Petal.Length, y = Petal.Width)) +
scale_color_manual(values = c("gray70","gray40","black")) +
theme(legend.position = c(0.2, 0.85)) +
labs(x = "Petal length (cm)",
y = "Petal width (cm)") +
theme(plot.title.position = "plot",
#panel.grid = element_blank(),
panel.border = element_rect(fill = NA, color = "gray70"),
legend.title = element_blank())
iris_tooltip <- c(str_c("Petal length = ", iris$Petal.Length,
"\n Petal width = ", iris$Petal.Width,
"\n Species = ", iris$Species))
iris_linear_int <-
iris_linear_base +
geom_point_interactive(aes(color = Species,
shape = Species,
tooltip = iris_tooltip,
data_id = Species),
size = 2,
alpha = .8
) +
geom_smooth_interactive(aes(group = Species,
color = Species,
data_id= Species),
method = lm,
se = FALSE
)
girafe(code = print(penguin_linear_int + iris_linear_int),
width_svg = 8,
height_svg = 4,
options = list(
opts_hover_inv(css = "opacity:0.2;"),
opts_hover(css = "opacity:1; filter: brightness(90%);")
))
```
:::
:::
::: notes
Allison presents
:::
## June 2020 \~4 months into lockdown ☣️
::: columns
::: {.column width="60%"}
- June 4: 🐦 In excitement, Allison Horst tweets about the penguins data
- 📦 Alison asks "Do you wanna build a package?"
- ❓Allison deletes tweet to sort out license
- 1 day later: 🔏 Allison emails Kristen about use & license
- 3 days later (June 8): 🚀 palmerpenguins power team assembles for the first time!
- Same day (June 8): 🏆 Allison Horst tweets (again) --- with clear license info
- 45 days later (July 23): 🎁 available on [CRAN](https://cran.r-project.org/web/packages/palmerpenguins/index.html)
:::
::: {.column width="40%"}
```{=html}
<blockquote class="twitter-tweet"><p lang="en" dir="ltr">🐧🐧🐧<br><br>This penguin data is a great alternative to iris & available for use by CC0 🤩 Thank you Dr. Kristen Gorman w/ <a href="https://twitter.com/UAFcfos?ref_src=twsrc%5Etfw">@UAFcfos</a>, Marty Downs w/ <a href="https://twitter.com/USLTER?ref_src=twsrc%5Etfw">@USLTER</a>, & <a href="https://twitter.com/PalmerLTER?ref_src=twsrc%5Etfw">@PalmerLTER</a> for help, info & making it available for use 🎉<br><br>Data, examples, & use info here: <a href="https://t.co/dSIqWNFlVw">https://t.co/dSIqWNFlVw</a> 🧵 1/6 <a href="https://t.co/2Eu4AxoeZl">pic.twitter.com/2Eu4AxoeZl</a></p>— Allison Horst (@allison_horst) <a href="https://twitter.com/allison_horst/status/1270046399418138625?ref_src=twsrc%5Etfw">June 8, 2020</a></blockquote> <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
```
:::
:::
::: notes
Allison presents
:::
## {background-image="img/iceberg.jpeg"}
### The making of... {.r-fit-text}
## For educators, by educators
```{r echo=TRUE}
library(palmerpenguins)
path_to_file()
path_to_file("penguins_raw.csv")
head(read.csv(path_to_file("penguins.csv")))
```
## To tibble or...
```{r echo=FALSE}
palmerpenguins::penguins
```
## Not to tibble, that is the question
> "I think this gives the best of both worlds --- if you're running in a low dependency environment, you'll get a data frame."
>
> --- Hadley Wickham[^2]
[^2]: Thanks to Hadley [for this PR!](https://github.com/allisonhorst/palmerpenguins/pull/25)
```{r echo=FALSE}
palmerpenguins::penguins %>%
as.data.frame()
```
::: notes
Alison HILL presents
:::
## {background-iframe="https://allisonhorst.github.io/palmerpenguins/"}
## Penguins in the wild {background-image="img/penguins-wilder.png" background-size="contain"}
::: notes
Alison HILL presents
:::
## Alison: Why has it been so popular?
- The R package format - so easy to just use
- Reduces time to first pretty plot
- [Allison's art](https://allisonhorst.github.io/palmerpenguins/articles/art.html)
[![Allison Horst's illustration of the 3 penguin species](img/allison-penguins.png){width="800"}](https://allisonhorst.github.io/palmerpenguins/articles/art.html)
## Allison: Why has it been so popular?
::: columns
::: column
The data itself---distributions, linearity
```{r}
#| fig.alt: "Scatterplots of bill depth versus body mass for the three penguin species, showing a positive linear relationship within species that switches to a negative linear relationship if species is omitted, an example of Simpson’s paradox."
# Simpson's Paradox example (body mass, omitting species):
bmass_nospecies_base <- penguins %>%
# doing this so ggiraph recognizes species across plots
mutate(species = as.character(species)) %>%
mutate(species = case_when(
species == "Adelie" ~ "Adélie",
TRUE ~ species)
) %>%
ggplot(aes(x = bill_depth_mm, y = body_mass_g)) +
theme(panel.border = element_rect(fill = NA, color = "gray70")) +
labs(x = "Bill depth (mm)", y = "Body mass (g)")
# Body mass, including species:
bmass_wspecies_base <-
penguins %>%
mutate(species = as.character(species)) %>%
mutate(species = case_when(
species == "Adelie" ~ "Adélie",
TRUE ~ species)
) %>%
ggplot(aes(x = bill_depth_mm, y = body_mass_g, group = species)) +
scale_color_paletteer_d("colorblindr::OkabeIto") +
theme(panel.border = element_rect(fill = NA, color = "gray70")) +
labs(x = "Bill depth (mm)", y = "Body mass (g)") +
guides(color = guide_legend("Species"),
shape = guide_legend("Species"))
nospecies_tooltip <- c(str_c("Bill depth (mm) = ", penguins$bill_depth_mm,
"\n Body mass (g) = ", penguins$body_mass_g,
"\n Species = ", penguins$species))
bmass_nospecies_int <-
bmass_nospecies_base +
geom_point_interactive(aes(tooltip = nospecies_tooltip,
data_id = species),
size = 2,
alpha = 0.8) +
geom_smooth_interactive(method = lm,
se = FALSE,
color = "black"
)
wspecies_tooltip <- c(str_c("Bill depth (mm) = ", penguins$bill_depth_mm,
"\n Body mass (g) = ", penguins$body_mass_g,
"\n Species = ", penguins$species))
bmass_wspecies_int <-
bmass_wspecies_base +
geom_point_interactive(aes(color = species,
shape = species,
tooltip = wspecies_tooltip,
data_id = species),
size = 2,
alpha = 0.8) +
geom_smooth_interactive(aes(color= species,
data_id= species),
method = lm,
se = FALSE
)
girafe(code = print(bmass_nospecies_int + bmass_wspecies_int),
width_svg = 6,
height_svg = 3,
options = list(
opts_hover_inv(css = "opacity:0.2;"),
opts_hover(css = "opacity:1; filter: brightness(90%);")
))
```
:::
::: column
Simpson's paradox examples in the wild!
```{r}
#| fig.alt: "Scatterplot of bill length versus bill depth for the three penguin species, showing a positive linear relationship within species. If species is omitted as a variable, the relationship switches to a negative trend, another example of Simpson’s paradox in the data"
# Simpson's Paradox example (bill dimensions, omitting species):
simpson_nospecies_base <- penguins %>%
# doing this so ggiraph recognizes species across plots
mutate(species = as.character(species)) %>%
mutate(species = case_when(
species == "Adelie" ~ "Adélie",
TRUE ~ species)
) %>%
ggplot(aes(x = bill_length_mm, y = bill_depth_mm)) +
theme(panel.border = element_rect(fill = NA, color = "gray70")) +
labs(x = "Bill length (mm)", y = "Bill depth (mm)")
# Bill dimensions, including species:
simpson_wspecies_base <-
penguins %>%
mutate(species = as.character(species)) %>%
mutate(species = case_when(
species == "Adelie" ~ "Adélie",
TRUE ~ species)
) %>%
ggplot(aes(x = bill_length_mm, y = bill_depth_mm, group = species)) +
scale_color_paletteer_d("colorblindr::OkabeIto") +
theme(panel.border = element_rect(fill = NA, color = "gray70")) +
labs(x = "Bill length (mm)", y = "Bill depth (mm)") +
guides(color = guide_legend("Species"),
shape = guide_legend("Species"))
nospecies_tooltip <- c(str_c("Bill length (mm) = ", penguins$bill_length_mm,
"\n Bill depth (g) = ", penguins$bill_depth_mm,
"\n Species = ", penguins$species))
simpson_nospecies_int <-
simpson_nospecies_base +
geom_point_interactive(aes(tooltip = nospecies_tooltip,
data_id = species),
size = 2,
alpha = 0.6) +
geom_smooth_interactive(method = lm,
se = FALSE,
color = "black"
)
wspecies_tooltip <- c(str_c("Bill length (mm) = ", penguins$bill_length_mm,
"\n Bill depth (g) = ", penguins$bill_depth_mm,
"\n Species = ", penguins$species))
simpson_wspecies_int <-
simpson_wspecies_base +
geom_point_interactive(aes(color = species,
shape = species,
tooltip = wspecies_tooltip,
data_id = species),
size = 2,
alpha = 0.6) +
geom_smooth_interactive(aes(color= species,
data_id= species),
method = lm,
se = FALSE
)
girafe(code = print(simpson_nospecies_int + simpson_wspecies_int),
width_svg = 6,
height_svg = 3,
options = list(
opts_hover_inv(css = "opacity:0.2;"),
opts_hover(css = "opacity:1; filter: brightness(90%);")
))
```
:::
:::
## Allison: Why has it been so popular?
Good bones for multivariate analyses
::: columns
::: column
Principle Components Analysis
```{r}
#| fig.alt: "Principal component biplot comparing results for penguins and iris, highlighting strong similarities between the two"
## ---- pca ---------------------------------------------------------
# From Alison Hill's post for palmerpenguins pkgdown site
### PENGUINS PCA:
# Omit year
penguins_noyr <- penguins %>%
select(-year) %>%
mutate(species = as.character(species)) %>%
mutate(species = case_when(
species == "Adelie" ~ "Adélie",
TRUE ~ species
)) %>%
mutate(species = as.factor(species))
penguin_recipe <-
recipe(~., data = penguins_noyr) %>%
update_role(species, island, sex, new_role = "id") %>%
step_naomit(all_predictors()) %>%
step_normalize(all_predictors()) %>%
step_pca(all_predictors(), id = "pca") %>%
prep()
penguin_pca <-
penguin_recipe %>%
tidy(id = "pca")
penguin_percvar <- penguin_recipe %>%
tidy(id = "pca", type = "variance") %>%
dplyr::filter(terms == "percent variance")
# Make the penguins PCA biplot:
# Get pca loadings into wider format
pca_wider <- penguin_pca %>%
tidyr::pivot_wider(names_from = component, id_cols = terms)
# define arrow style:
arrow_style <- arrow(length = unit(.05, "inches"),
type = "closed")
penguins_juiced <- juice(penguin_recipe)
# Make the penguins PCA biplot:
pca_plot <-
penguins_juiced %>%
ggplot(aes(PC1, PC2)) +
coord_cartesian(
xlim = c(-3, 4),
ylim = c(-2.5, 2)) +
scale_color_paletteer_d("colorblindr::OkabeIto") +
guides(color = guide_legend("Species"),
shape = guide_legend("Species")) +
theme(legend.position = "bottom",
panel.border = element_rect(color = "gray70", fill = NA))
# For positioning (above):
# 1: bill_length
# 2: bill_depth
# 3: flipper length
# 4: body mass
penguins_biplot <- pca_plot +
geom_segment(data = pca_wider,
aes(xend = PC1, yend = PC2),
x = 0,
y = 0,
arrow = arrow_style) +
geom_point(aes(color = species, shape = species),
alpha = 0.7,
size = 2) +
geom_shadowtext(data = pca_wider,
aes(x = PC1, y = PC2, label = terms),
nudge_x = c(0.7,0.7,1.7,1.2),
nudge_y = c(-0.1,-0.2,0.1,-0.1),
size = 4,
color = "black",
bg.color = "white")
### IRIS PCA:
iris_recipe <-
recipe(~., data = iris) %>%
update_role(Species, new_role = "id") %>%
step_normalize(all_predictors()) %>%
step_pca(all_predictors(), id = "pca") %>%
prep()
iris_pca <-
iris_recipe %>%
tidy(id = "pca")
### Iris PCA biplot:
# Get pca loadings into wider format
iris_wider <- iris_pca %>%
tidyr::pivot_wider(names_from = component, id_cols = terms)
# define arrow style:
arrow_style <- arrow(length = unit(.05, "inches"),
type = "closed")
iris_juiced <- juice(iris_recipe)
# Make the iris PCA biplot:
iris_pca_plot <-
iris_juiced %>%
ggplot(aes(PC1, PC2)) +
coord_cartesian(
xlim = c(-3, 3),
ylim = c(-3, 3)) +
scale_colour_manual(values = c("gray70","gray40","black")) +
theme(panel.background = element_rect(fill = NA, color = "gray70"),
legend.position = "bottom")
iris_biplot <- iris_pca_plot +
geom_point(aes(color = Species, shape = Species),
alpha = 0.8,
size = 2) +
geom_segment(data = iris_wider,
aes(xend = PC1, yend = PC2),
x = 0,
y = 0,
arrow = arrow_style) +
geom_shadowtext(data = iris_wider,
aes(x = PC1, y = PC2, label = terms),
nudge_x = c(0.5,0.3,1,1.2),
nudge_y = c(-0.1,-0.2,0.1,-0.1),
size = 4,
color = "black",
bg.color = "white")
penguins_biplot_tooltip <- str_c("Species = ", penguins_juiced$species,
"\n PC1 = ", round(penguins_juiced$PC1, 2),
"\n PC2 = ", round(penguins_juiced$PC2, 2))
penguins_biplot_int <- pca_plot +
geom_segment_interactive(data = pca_wider,
aes(xend = PC1, yend = PC2),
x = 0,
y = 0,
arrow = arrow_style) +
geom_point_interactive(aes(color = species, shape = species,
tooltip = penguins_biplot_tooltip,
data_id = species),
alpha = 0.7,
size = 2) +
geom_shadowtext(data = pca_wider,
aes(x = PC1, y = PC2, label = terms),
nudge_x = c(0.7,0.7,1.7,1.2),
nudge_y = c(-0.1,-0.2,0.1,-0.1),
size = 4,
color = "black",
bg.color = "white")
# girafe(ggobj = penguins_biplot_int)
iris_biplot_tooltip <- str_c("Species = ", iris_juiced$Species,
"\n PC1 = ", round(iris_juiced$PC1, 2),
"\n PC2 = ", round(iris_juiced$PC2, 2))
iris_biplot_int <- iris_pca_plot +
geom_segment_interactive(data = iris_wider,
aes(xend = PC1, yend = PC2),
x = 0,
y = 0,
arrow = arrow_style) +
geom_point_interactive(aes(color = Species, shape = Species,
tooltip = iris_biplot_tooltip,
data_id = Species),
alpha = 0.7,
size = 2) +
geom_shadowtext(data = iris_wider,
aes(x = PC1, y = PC2, label = terms),
nudge_x = c(0.5,0,1,1),
nudge_y = c(-0.1,-0.2,0.2,-0.1),
size = 4,
color = "black",
bg.color = "white")
girafe(code = print(penguins_biplot_int | iris_biplot_int),
width_svg = 6,
height_svg = 3,
options = list(
opts_hover_inv(css = "opacity:0.2;"),
opts_hover(css = "opacity:1; filter: brightness(90%);")
))
```
:::
::: column
K-means
```{r}
#| fig.alt: "Compared k-means clustering scatterplots for penguins and iris."
## ---- kmeans ---------------------------------------------------------
# TWO VARIABLE k-means comparison
# Penguins: Bill length vs. bill depth
pb_species <- penguins %>%
select(species, starts_with("bill")) %>%
drop_na() %>%
mutate(species = as.character(species)) %>%
mutate(species = case_when(
species == "Adelie" ~ "Adélie",
TRUE ~ species
)) %>%
mutate(species = as.factor(species))
# Prep penguins for k-means:
pb_nospecies <- pb_species %>%
select(-species) %>%
recipe() %>%
step_normalize(all_numeric()) %>%
prep() %>%
juice()
# Perform k-means on penguin bill dimensions (k = 3, w/20 centroid starts)
# Save augmented data
set.seed(100)
pb_clust <-
pb_nospecies %>%
kmeans(centers = 3, nstart = 20) %>%
broom::augment(pb_species)
# Get counts in each cluster by species
pb_clust_n <- pb_clust %>%
count(species, .cluster) %>%
pivot_wider(names_from = species, values_from = n, names_sort = TRUE) %>%
arrange(.cluster) %>%
replace_na(list(`Adelie` = 0))
### Iris k-means
# Iris: petal length vs. petal width
# Select only petal dimensions:
ip_species <- iris %>%
select(Species, starts_with("Petal"))
# Remove species factor & scale petal dimensions:
ip_nospecies <- ip_species %>%
select(-Species) %>%
recipe() %>%
step_normalize(all_numeric()) %>%
prep() %>%
juice()
# Perform k-means on iris petal dimensions (k = 3, w/20 centroid starts):
set.seed(100)
ip_clust <-
ip_nospecies %>%
kmeans(centers = 3, nstart = 20) %>%
broom::augment(ip_species)
# Get iris counts in each cluster by species:
ip_clust_n <- ip_clust %>%
count(Species, .cluster) %>%
pivot_wider(names_from = Species, values_from = n, names_sort = TRUE) %>%
arrange(.cluster) %>%
replace_na(list(`setosa` = 0, `versicolor` = 0, `virginica` = 0))
# Plot penguin k-means clusters:
# make a base plot b/c https://github.com/plotly/plotly.R/issues/1942
pb_kmeans_base <-
pb_clust %>%
ggplot(aes(x = bill_length_mm, y = bill_depth_mm)) +
scale_color_paletteer_d("colorblindr::OkabeIto") +
scale_fill_paletteer_d("colorblindr::OkabeIto") +
scale_x_continuous(limits = c(30, 60),
breaks = c(30, 40, 50, 60)) +
theme(legend.position = "bottom",
panel.border = element_rect(fill = NA, color = "gray70")) +
labs(x = "Bill length (mm)",
y = "Bill depth (mm)",
color = "Species")
# Plot iris k-means clusters:
# make a base plot b/c https://github.com/plotly/plotly.R/issues/1942
ip_kmeans_base <-
ip_clust %>%
ggplot(aes(x = Petal.Length, y = Petal.Width)) +
theme(legend.position = "bottom",
panel.border = element_rect(fill = NA, color = "gray70")) +
scale_color_manual(values = c("gray70","gray50","black")) +
labs(x = "Petal length (cm)",
y = "Petal width (cm)")
pb_tooltip <- str_c("Cluster: ", pb_clust$.cluster,
"\n Species: ", pb_clust$species,
"\n Bill length (mm): ", pb_clust$bill_length_mm,
"\n Bill depth (mm) : ", pb_clust$bill_depth_mm)
pb_kmeans_int <- pb_kmeans_base +
geom_text_interactive(aes(
label = .cluster,
color = species,
tooltip = pb_tooltip,
data_id = species),
size = 3,
check_overlap = TRUE)
ip_tooltip <- str_c("Cluster: ", ip_clust$.cluster,
"\n Species: ", ip_clust$Species,
"\n Petal Length (cm): ", ip_clust$Petal.Length,
"\n Petal Width (cm): ", ip_clust$Petal.Width)
ip_kmeans_int <- ip_kmeans_base +
geom_text_interactive(aes(
label = .cluster,
color = Species,
tooltip = ip_tooltip,
data_id = Species),
size = 3,
check_overlap = TRUE)
girafe(code = print(pb_kmeans_int + ip_kmeans_int),
width_svg = 6,
height_svg = 3,
options = list(
opts_hover_inv(css = "opacity:0.1;"),
opts_hover(css = "opacity:1; filter: brightness(90%);")
))
```
:::
:::
## Kristen: Why has it been so popular?
::: columns
::: column
- Penguins! (rare to see IRL, but so easy to see & say)
- Understandable structural measurements
- [Open license](https://allisonhorst.github.io/palmerpenguins/LICENSE.html) underlying the data
- Ecology of species is relevant to global climate change
:::
::: column
![Penguin bills art by Allison Horst](https://allisonhorst.github.io/palmerpenguins/reference/figures/culmen_depth.png){alt="Penguin bills art by Allison Horst" fig-alt="Penguin bill length is measured from start to tip of bill, whereas bill depth is measured from top of bill to bottom" fig-align="right"}
:::
:::
::: notes
Kristen presents
:::
## From polar research project to global teaching product
::: columns
::: column
- Antarctic data should be available to the world - no geopolitical boundaries
- When you collect data as a scientist, you are collecting knowledge that you may not even imagine how it will be used
:::
::: column
![Map of Antarctica by Kristen Gorman](img/antarctic-modis.jpg){fig-alt="Map of Antarctica by Kristen Gorman" fig-align="center"} <!--[![Map of Antarctica by R. M. Chapin](img/map.jpg){fig-alt="Map of Antarctica by R. M. Chapin" fig-align="center"}](https://www.flickr.com/photos/crossettlibrary/6941620363)-->
:::
:::
## Thank you!
What questions do you have?
We wish to thank:
- Marty Downs at LTER
- Hadley Wickham (RStudio)
- Laura Navarro for [this plot](https://lauranavarroviz.wordpress.com/2020/08/01/palmer-penguins/)
- Cédric Scherer for [this plot](https://www.behance.net/gallery/101517403/Bill-Dimensions-of-Penguins)
- Silvia Canelón for her [great tutorial](https://www.silviacanelon.com/talk/2020-tour-of-the-tidyverse/)
- The #rstats community for blogging, tweeting, visualizing, analyzing, teaching, and sharing about `palmerpenguins`