-
Notifications
You must be signed in to change notification settings - Fork 0
/
copenhagenR-April2024-slides.qmd
1481 lines (1119 loc) · 44.8 KB
/
copenhagenR-April2024-slides.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
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
# title: "My Year of Riding Danishly"
# author: "Gregers Kjerulf Dubrow"
format:
revealjs:
theme: [default, custom.scss]
center-title-slide: false
# title-slide-attributes:
# data-background-image: "bike_dragor.jpeg"
# data-background-size: contain
slide-number: c/t
code-link: true
code-overflow: wrap
code-block-height: 1500px
code-line-numbers: false
height: 1080
width: 1920
editor: source
---
##
````{=html}
<!---makes code chunk font larger
```{css echo=FALSE}
.big-code{
font-size: 125%
}
```
--->
````
<center>
<h1>My Year of Riding Danishly</h1>
</center>
<br> <br> <br> <br> <br>
<h2>Gregers Kjerulf Dubrow</h2>
<br>
<h3>CopenhagenR</h3>
<br>
<h3>23 April, 2024</h3>
::: {.absolute bottom="50" right="-400"}
![](images/bike_dragor.jpeg){width="75%" fig-alt="red univega road bike overlooking oresund at dragor"}
:::
##
<center>
<h1>My Year of Riding Danishly</h1>
</center>
::: columns
::: {.column .fragment width="50%"}
<br> <!---<div class=big-code> --->
```{r}
#| eval: false
#| echo: true
library(gregbio)
my_life <- blev_født(danmark) %>%
```
<!---</div> --->
:::
:::
::: {.fragment .absolute top="185" right="400"}
![](images/me_drive.jpg){width="4in" fig-alt="6 month old baby at the steering wheel of a car"}
:::
##
<center>
<h1>My Year of Riding Danishly</h1>
</center>
::: columns
::: {.column width="55%"}
<br>
```{r}
#| eval: false
#| echo: true
library(gregbio)
my_life <- blev_født(danmark) %>%
voksede_op(USA,
state = “Pennsylvania”,
city = “Philadelphia) %>%
undergrad_degree(film_major) %>%
PhD(education_policy) %>%
```
:::
:::
::: {.absolute top="185" right="400"}
![](images/me_drive.jpg){width="4in" fig-alt="6 month old baby at the steering wheel of a car"}
:::
::: {.absolute top="185" right="70"}
![](images/philadelphia_city_hall.jpeg){width="3.5in" fig-alt="philadelphia pa city hall"}
:::
##
<center>
<h1>My Year of Riding Danishly</h1>
</center>
::: columns
::: {.column width="55%"}
<br>
```{r}
#| eval: false
#| echo: true
library(gregbio)
my_life <- blev_født(danmark) %>%
voksede_op(USA,
state = “Pennsylvania”,
city = “Philadelphia) %>%
undergrad_degree(film_major) %>%
PhD(education_policy) %>%
career = case_when(
job = faculty ~ FIU, (set_location as Miami, FL)
```
:::
:::
::: {.absolute top="185" right="400"}
![](images/me_drive.jpg){width="4in" fig-alt="6 month old baby at the steering wheel of a car"}
:::
::: {.absolute top="185" right="70"}
![](images/philadelphia_city_hall.jpeg){width="3.5in" fig-alt="philadelphia pa city hall"}
:::
::: {.absolute top="450" right="435"}
![](images/miamibeach.jpeg){width="3.5in" fig-alt="miami beach lifeguard station"}
:::
##
<center>
<h1>My Year of Riding Danishly</h1>
</center>
::: columns
::: {.column width="55%"}
<br>
```{r}
#| eval: false
#| echo: true
library(gregbio)
my_life <- blev_født(danmark) %>%
voksede_op(USA,
state = “Pennsylvania”,
city = “Philadelphia) %>%
undergrad_degree(film_major) %>%
PhD(education_policy) %>%
career = case_when(
job = faculty ~ FIU, (set_location as Miami, FL),
job = data_analyst ~ UC Berkeley & SFSU,
(set_location as SF Bay Area)
```
:::
:::
::: {.absolute top="185" right="400"}
![](images/me_drive.jpg){width="4in" fig-alt="6 month old baby at the steering wheel of a car"}
:::
::: {.absolute top="185" right="70"}
![](images/philadelphia_city_hall.jpeg){width="3.5in" fig-alt="philadelphia pa city hall"}
:::
::: {.absolute top="450" right="435"}
![](images/miamibeach.jpeg){width="3.5in" fig-alt="miami beach lifeguard station"}
:::
::: {.absolute top="450" right="70"}
![](images/sproulhall.jpeg){width="3.5in" fig-alt="overhead shot of sproul hall uc berkeley"}
:::
##
<center>
<h1>My Year of Riding Danishly</h1>
</center>
::: columns
::: {.column width="55%"}
<br>
```{r}
#| eval: false
#| echo: true
library(gregbio)
my_life <- blev_født(danmark) %>%
voksede_op(USA,
state = “Pennsylvania”,
city = “Philadelphia) %>%
undergrad_degree(film_major) %>%
PhD(education_policy) %>%
career = case_when(
job = faculty ~ FIU, (set_location as Miami, FL),
job = data_analyst ~ UC Berkeley & SFSU,
(set_location as SF Bay Area),
job = career_swerve1 ~ freelance_ESL_teacher,
(set_location as Lyon, FR)
```
:::
:::
::: {.absolute top="185" right="400"}
![](images/me_drive.jpg){width="4in" fig-alt="6 month old baby at the steering wheel of a car"}
:::
::: {.absolute top="185" right="70"}
![](images/philadelphia_city_hall.jpeg){width="3.5in" fig-alt="philadelphia pa city hall"}
:::
::: {.absolute top="450" right="435"}
![](images/miamibeach.jpeg){width="3.5in" fig-alt="miami beach lifeguard station"}
:::
::: {.absolute top="450" right="70"}
![](images/sproulhall.jpeg){width="3.5in" fig-alt="overhead shot of sproul hall uc berkeley"}
:::
::: {.absolute top="710" right="435"}
![](images/lyon_jardincuriousity.jpeg){width="3.5in" fig-alt="lyon france"}
:::
##
<center>
<h1>My Year of Riding Danishly</h1>
</center>
::: columns
::: {.column width="55%"}
<br>
```{r}
#| eval: false
#| echo: true
library(gregbio)
my_life <- blev_født(danmark) %>%
voksede_op(USA,
state = “Pennsylvania”,
city = “Philadelphia) %>%
undergrad_degree(film_major) %>%
PhD(education_policy) %>%
career = case_when(
job = faculty ~ FIU, (set_location as Miami, FL),
job = data_analyst ~ UC Berkeley & SFSU,
(set_location as SF Bay Area),
job = career_swerve1 ~ freelance_ESL_teacher,
(set_location as Lyon, FR)
job = career_swerve2 ~
study_abroad_student_services,
(set_location as København, DK)))
```
:::
:::
::: {.absolute top="185" right="400"}
![](images/me_drive.jpg){width="4in" fig-alt="6 month old baby at the steering wheel of a car"}
:::
::: {.absolute top="185" right="70"}
![](images/philadelphia_city_hall.jpeg){width="3.5in" fig-alt="philadelphia pa city hall"}
:::
::: {.absolute top="450" right="435"}
![](images/miamibeach.jpeg){width="3.5in" fig-alt="miami beach lifeguard station"}
:::
::: {.absolute top="450" right="70"}
![](images/sproulhall.jpeg){width="3.5in" fig-alt="overhead shot of sproul hall uc berkeley"}
:::
::: {.absolute top="710" right="435"}
![](images/lyon_jardincuriousity.jpeg){width="3.5in" fig-alt="lyon france"}
:::
::: {.absolute top="710" right="70"}
![](images/CIEE.jpeg){width="3.5in" fig-alt="front door to ciee copenhagen study center"}
:::
##
<center>
<h1>My Year of Riding Danishly</h1>
</center>
<center>https://www.gregdubrow.io/posts/my-year-of-riding-danishly/</center>
![](images/blogpostscreenshot.png){fig-align="center" height="10in"}
## The plan...
- [Pull the Data](#getdata)
- Via bulk download, the Strava API, and `rStrava` package.
- [EDA with DataExplorer](#eda1)
- Show and run code for exploratory analysis (EDA) using the `DataExplorer` package.
- [EDA with Automated Scatterplots](#eda2)
- Show and run code for EDA using [Cedric Scherer's tutorial on automating plots](https://www.cedricscherer.com/2023/07/05/efficiency-and-consistency-automate-subset-graphics-with-ggplot2-and-purrr/).
- [Tables with `gt`](#tables)
- Show and run code for the tables, including how to align `gt` tables next to each other.
- [Create Charts to Describe My Ride Data](#plots)
- Show and run the `ggplot` code to make some pretty charts.
- [Regression Models](#models)
- Run a few regression models to explain ride outcomes.
## What is Strava?
![](images/strava.jpeg){fig-align="left" height="2in"}
. . .
<h2>
- App & data platform to track physical exercise - mostly cycling, running, and walking/hiking.
</h2>
. . .
<h2>
- Uses Global Positioning System (GPS) to plot routes.
</h2>
. . .
<h2>
- Social media features, including following other users, adding photos to activity posts, giving kudos to other users on their activities...
</h2>
. . .
<h2>
- Name derived from Swedish word for "strive" - `sträva`
</h2>
## Pulling the data - Bulk download
- Bulk download includes folder with all activities in GPX (GPS Exchange Format) files to build your own maps.
::: {.absolute top="190" left="10"}
![](images/stravabulkfolder1a.png){width="5.3in" fig-alt="strava download folder"}
:::
::: {.absolute top="190" left="600"}
![](images/stravabulkfolder2.png){width="3in" fig-alt="strava download folder activities"}
:::
::: {.absolute top="190" left="950"}
![](images/stravagpx.png){fig-alt="strava download folder activities"}
:::
## Pulling the data - API
- Sign up in your account, project can be anything you want.
::: {.fragment .absolute top="190" left="10"}
![](images/strava_authreq.png){width="8in" fig-alt="strava download folder"}
:::
::: {.fragment .absolute top="190" left="800"}
![](images/strava_apipage.png){width="8in" fig-alt="strava download folder activities"}
:::
## Pulling the data - API
![](images/strava_api_ref.png){fig-alt="strava api developer page" fig-align="center" height="11in"}
## Pulling the data - `rStrava` package
<center>https://github.com/fawda123/rStrava</center>
![](images/rstrava_github.png){fig-align="center" height="11in"}
## Let's load the CSV data
```{r}
#| eval: false
#| echo: true
library(tidyverse) # to do tidyverse things
library(tidylog) # to get a log of what's happening to the data
library(janitor) # tools for data cleaning
strava_activities <- readr::read_csv("data/activities.csv") %>%
clean_names() %>%
as_tibble() %>%
rename(elapsed_time = elapsed_time_6, distance = distance_7, max_heart_rate = max_heart_rate_8,
relative_effort = relative_effort_9, commute = commute_10, elapsed_time2 = elapsed_time_16,
distance2 = distance_18, relative_effort2 = relative_effort_38, commute2 = commute_51)
```
::: {.fragment}
![](images/activitycsv1.png){width="11in"}
:::
::: {.fragment}
![](images/strava_act2673634672.png)
:::
## Too much date & time wrangling
```{r}
#| eval: false
#| echo: true
mutate(activity_date = str_replace(activity_date, "Jan ", "January "))
separate('activity_date', paste("date", 1:3, sep="_"), sep=",", extra="drop")
mutate(activity_md = str_trim(date_1))
separate('activity_md', paste("activity_md", 1:2, sep="_"), sep=" ", extra="drop")
mutate(activity_mdy = paste0(date_1, ",", date_2))
mutate(activity_ymd = lubridate::mdy(activity_mdy))
mutate(activity_tz = case_when(activity_ymd >= "2022-06-28" ~ "Europe/Copenhagen",
TRUE ~ "US/Pacific"))
```
<br>
::: {.fragment}
<h3>Ok, time to try the API...or wait...is there a package?</h3>
:::
::: {.fragment}
![](images/rstava_bsky.png){height=4.75in}
:::
## Using the `rStrava` package - Authorization
In a separate file called stoken.r, I create the access token to call in the script that pulls the data.
```{r}
#| eval: false
#| echo: true
library(rStrava)
app_name <- 'Year of Riding Danishly' # chosen by user
app_client_id <- '---' # an integer, assigned by Strava
app_secret <- '---' # an alphanumeric secret, assigned by Strava
# create the authentication token - cache = TRUE saves it in the working directory
stoken <- httr::config(token = strava_oauth(
app_name, app_client_id, app_secret,
app_scope="activity:read_all", cache = TRUE))
```
stoken object is a list:
::: {.fragment}
![](images/stoken.png){height=7in}
:::
## Using the `rStrava` package - Get the data
```{r}
#| eval: false
#| echo: true
## call the OAuth access token
stoken <- httr::config(token = readRDS('.httr-oauth')[[1]])
## invoke stoken to get data
myact <- get_activity_list(stoken)
```
Returns a list of activities requested
::: {.fragment .absolute top="300" left="10"}
![](images/rstrava_activity1.png){height=6in}
:::
::: {.fragment .absolute top="300" left="720"}
![](images/rstrava_activity2.png){height=9.5in}
:::
## Using the `rStrava` package - Get the data
```{r}
#| eval: false
#| echo: true
act_data <- compile_activities(myact) %>%
as_tibble() %>%
glimpse()
```
::: {.fragment}
![](images/activity_glimpse.png){height=10in}
:::
## Clean & prep the data
```{r}
#| eval: false
#| echo: true
act_data <- compile_activities(myact) %>%
as_tibble() %>%
mutate(gear_name = case_when(gear_id == "b6298198" ~ "Univega",
gear_id == "b11963967" ~ "Commute bike", TRUE ~ "Not a bike ride")) %>%
mutate(activity_date = lubridate::as_datetime(start_date_local)) %>%
mutate(activity_date_p = as.Date(start_date_local)) %>%
mutate(activity_year = lubridate::year(start_date_local),
activity_month = lubridate::month(start_date_local),
activity_month_t = lubridate::month(start_date_local, label = TRUE, abbr = FALSE),
activity_day = lubridate::day(start_date_local),
activity_md = paste0(activity_month_t, " ", activity_day),
activity_wday = wday(activity_date_p, label = TRUE, abbr = FALSE),
activity_hour = lubridate::hour(activity_date),
activity_min = lubridate::minute(activity_date),
activity_hmt = paste0(activity_hour, ":", activity_min),
activity_hm = hm(activity_hmt),
moving_time_hms = hms::hms(moving_time),
elapsed_time_hms = hms::hms(elapsed_time)) %>%
mutate(location_country = case_when(
timezone == "(GMT+01:00) Europe/Copenhagen" ~ "Denmark",
timezone == "(GMT+01:00) Europe/Paris" ~ "France", TRUE ~ "United States")) %>%
## random edits
mutate(commute = ifelse((activity_year == 2023 & activity_md == "June 14" & name == "Morning commute"),
TRUE, commute))
## merge with variables from CSV but not in API
act_data_csv_ext <- act_data_csv %>%
select(activity_id, calories, average_grade, max_grade, average_elapsed_speed, elevation_loss)
strava_activities_final <- act_data %>%
merge(act_data_csv_ext) %>%
select(activity_id:max_speed, average_elapsed_speed, elevation_gain, elevation_loss, elevation_high, elevation_low,
average_grade, max_grade, location_country:lng_end, average_watts, calories, kilojoules)
```
## Let's do some EDA
<!---load data quietly--->
```{r dataload, message=FALSE, ECHO = FALSE, include = FALSE}
#| message: false
#| echo: false
#| include: false
#| warning: false
#| error: false
library(tidyverse) # to do tidyverse things
library(tidylog) # to get a log of what's happening to the data
library(janitor) # tools for data cleaning
library(modelsummary) # regressions
library(ggtext) # ggplot text helpers
## quietly loads RDS already created
strava_data <- readRDS("~/Data/r/year of riding danishly/data/strava_activities_final.rds")
sumtable <- readRDS("~/Data/r/year of riding danishly/data/sumtable.rds")
rides_mth_type <- readRDS("~/Data/r/year of riding danishly/data/rides_mth_type.rds")
activty_ampm <- readRDS("~/Data/r/year of riding danishly/data/activty_ampm.rds")
strava_models <- strava_data %>%
filter(activity_year == 2023)
```
```{r eda2l}
#| eval: false
#| echo: true
library(DataExplorer) # for EDA
plot_intro(strava_data)
plot_missing(strava_data)
```
::: {.absolute top="250" left="10"}
![](images/plot_intro.png){height=8in}
:::
::: {.absolute top="250" left="850"}
![](images/plot_miss.png){height=8in}
:::
## Quick aside...some terms that need defining
<br>
Some are obvious (distance in km), these maybe less so...
. . .
- Elapsed time: When I hit "start" on the app to when I hit "stop".
. . .
- Moving time: App's caclulation of how much time was spent in motion.
. . .
- Grade: Rise (elevation) divided by run (distance), x 100
. . .
- Watts: A measurement of power. Strava incorporates rider weight, bike weight, bike type, gradients and speed.
. . .
- Calories: Total energy expended in the time it took to do the workout.
. . .
- Kilojoules: Energy burned by the workout. Formula for kilojoules is (watts x seconds) x 1000.
## Let's do some EDA - Correlations!
```{r edacorrr}
#| eval: false
#| echo: true
strava_data %>%
select(distance_km, elapsed_time, moving_time, max_speed, average_speed, elevation_gain, elevation_loss, elevation_low,
elevation_high, average_grade, max_grade, average_watts, calories, kilojoules) %>%
filter(!is.na(average_watts)) %>%
filter(!is.na(calories)) %>%
plot_correlation(maxcat = 5L, type = "continuous", geom_text_args = list("size" = 4))
```
::: {.fragment .absolute top="290" left="10"}
![](images/eda_corr.png){height=9in}
:::
::: {.fragment .absolute top="290" left="875"}
So what do we see here?
- Most of the relationships are positive, some with expectedly near 1:1 relationships, such as distance (in km) and total time for the ride.
- Average speed is positively correlated with distance but the relationship is only at 0.14, the weakest of all positive associations with distance. Average speed correlations are low...near 0, for total elevation gain and negative the higher the average grade of the ride.
- Averge watts, or weighted power output for the ride, has mostly negative correlations. Longer rides in time or distance meant a lower average power per ride segment.
We'll keep these correlations in mind when looking at the scatterplots and then later considering the regression results.
:::
## More EDA - Scatterplots!
- `DataExplorer` has functionality for scatterplots, but each call only allows for one comparison y-axis variable & not much customization to the output, like a smoothing line.
```{r}
#| eval: false
#| echo: true
plot_scatterplot(strava_data_filter, by = "distance_km", nrow = 6L)
```
![](images/scatterplot_de.png){height=9in}
## More EDA - Better scatterplots!
- https://www.cedricscherer.com/2023/07/05/efficiency-and-consistency-automate-subset-graphics-with-ggplot2-and-purrr/
```{r}
#| eval: false
#| echo: true
plot_scatter_lm <- function(data, var1, var2, pointsize = 2, transparency = .5, color = "") {
## check if inputs are valid
if (!exists(substitute(data))) stop("data needs to be a data frame.")
if (!is.data.frame(data)) stop("data needs to be a data frame.")
if (!is.numeric(pull(data[var1]))) stop("Column var1 needs to be of type numeric, passed as string.")
if (!is.numeric(pull(data[var2]))) stop("Column var2 needs to be of type numeric, passed as string.")
if (!is.numeric(pointsize)) stop("pointsize needs to be of type numeric.")
if (!is.numeric(transparency)) stop("transparency needs to be of type numeric.")
if (color != "") { if (!color %in% names(data)) stop("Column color needs to be a column of data, passed as string.") }
g <-
ggplot(data, aes(x = !!sym(var1), y = !!sym(var2))) +
geom_point(aes(color = !!sym(color)), size = pointsize, alpha = transparency) +
geom_smooth(aes(color = !!sym(color), color = after_scale(prismatic::clr_darken(color, .3))),
method = "lm", se = FALSE) +
theme_minimal() +
theme(panel.grid.minor = element_blank(), legend.position = "top")
if (color != "") {
if (is.numeric(pull(data[color]))) {
g <- g + scale_color_viridis_c(direction = -1, end = .85) +
guides(color = guide_colorbar(
barwidth = unit(12, "lines"), barheight = unit(.6, "lines"), title.position = "top"))
} else {g <- g + scale_color_brewer(palette = "Set2")}
}
return(g)
}
```
## More EDA - Better scatterplots!
```{r}
#| eval: false
#| echo: true
## 1st plot call - distance as y axis
patchwork::wrap_plots(
map2(c("elapsed_time", "moving_time", "average_speed","average_watts", "calories", "kilojoules"),
c("distance_km", "distance_km", "distance_km", "distance_km", "distance_km", "distance_km"),
~plot_scatter_lm(data = strava_activities_rides, var1 = .x, var2 = .y, pointsize = 3.5) +
theme(plot.margin = margin(rep(15, 4)))))
```
::: {.fragment}
![](images/scatterplot_dist.png){height=6.5in}
:::
::: {.fragment .absolute top="300" left="1200"}
- Confirms what we saw in the correlation heatmap & displays ride distributions.
- Positive and almost 1:1 relationships between distance and both time measures, elapsed and moving.
- Negative association with watts that we saw in the correlations. Making a note to take a closer look at how much an effect watts has later on in the regression section.
- Note the outlier ride of 60km and an elapsed time of more than 15,000 seconds...more about that one later.
:::
## A few more scatterplots
::: {.absolute top="80" left="10"}
![](images/scatterplot_time.png){height=5in}
:::
::: {.absolute top="80" left="900"}
![](images/scatterplot_speed.png){height=5in}
:::
::: {.absolute top="600" left="10"}
![](images/scatterplot_kjoule.png){height=5in}
:::
::: {.absolute top="600" left="900"}
- Average speed decreases as ride time goes up (top left plot)...makes sense.
- Expended more energy (calories & kilojoules) as ride time increased (top left).
- Speed & watts had strong relationship (top right), as we saw in correlation heatmap.
- Surprised energy output has weak association with average speed; perhaps here in flat Denmark there’s only so much energy burn I can hit.
- Strong relationship between kilojoules & elevation.
:::
## Tables with `gt`
```{r}
#| fig.width: 8.0
#| fig.height: 6.0
#| fig-dpi: 300
#| warning: false
#| message: false
#| error: false
#| echo: false
library(gt)
sumtable %>%
select(rides, km_total, elev_total, time_total1, time_total2, cal_total, kiloj_total) %>%
gt() %>%
fmt_number(columns = c(km_total, elev_total, cal_total, kiloj_total), decimals = 0) %>%
cols_label(rides = "Total Rides", km_total = "Total Kilometers",
elev_total = md("Total Elevation *(meters)*"),
time_total1 = md("Total Time *(hours/min/sec)*"),
time_total2 = md("Total Time *(days/hours/min/sec)*"),
cal_total = "Total Calories", kiloj_total = "Total Kilojoules") %>%
cols_align(align = "center", columns = everything()) %>%
tab_style(style = cell_fill(color = "lightgrey"),
locations = cells_body(rows = seq(1, 1, 1))) %>%
tab_style(
style = cell_text(align = "center"),
locations = cells_column_labels(
columns = c(rides, km_total, elev_total, time_total1, time_total2, cal_total, kiloj_total))) %>%
tab_header(title = md("My Year of Riding Danishly<br>*Ride Totals*")) %>%
gtsave("images/gtsummary1.png")
```
```{r}
#| eval: false
#| echo: true
library(gt)
sumtable %>%
select(rides, km_total, elev_total, time_total1, time_total2, cal_total, kiloj_total) %>%
gt() %>%
fmt_number(columns = c(km_total, elev_total, cal_total, kiloj_total), decimals = 0) %>%
cols_label(rides = "Total Rides", km_total = "Total Kilometers",
elev_total = md("Total Elevation *(meters)*"),
time_total1 = md("Total Time *(hours/min/sec)*"),
time_total2 = md("Total Time *(days/hours/min/sec)*"),
cal_total = "Total Calories", kiloj_total = "Total Kilojoules") %>%
cols_align(align = "center", columns = everything()) %>%
tab_style(style = cell_fill(color = "grey"), locations = cells_body(rows = seq(1, 1, 1))) %>%
tab_style( style = cell_text(align = "center"), locations = cells_column_labels(
columns = c(rides, km_total, elev_total, time_total1, time_total2, cal_total, kiloj_total))) %>%
tab_header(title = md("My Year of Riding Danishly<br>*Ride Totals*"))
```
::: {.fragment}
![](images/gtsummary1.png)
:::
::: {.fragment}
- For the year, more than 440 rides covering 2,500 kilometers.
- I spent the equivalent of more than 5 days on the bike, and burned 60,000+ units of energy. Which means on average, every day I did 1.2 rides,and went about 7 km, a few km more than the average Copenhagener. (*It occurs to me know that I didn't make a count for how many days of the year I rode...an edit to come perhaps...*)
:::
## Tables with `gt`
```{r}
#| fig.width: 8.0
#| fig.height: 6.0
#| fig-dpi: 300
#| warning: false
#| message: false
#| error: false
#| echo: false
sumtable %>%
select(km_avg, km_med, km_min, km_max) %>%
gt() %>%
cols_label(km_avg = "Average", km_med = "Median",
km_min = "Shortest", km_max = "Longest") %>%
cols_align(align = "center", columns = everything()) %>%
tab_style(style = cell_fill(color = "grey"), locations = cells_body(rows = seq(1, 1, 1))) %>%
tab_header(title = md("*Ride Statistics - Distance (in km)*")) %>%
gtsave("images/gtsummary2.png")
sumtable %>%
select(time_avg, time_med, time_min, time_max) %>%
gt() %>%
cols_label(time_avg = "Average", time_med = "Median",
time_min = "Shortest", time_max = "Longest") %>%
cols_align(align = "center", columns = everything()) %>%
tab_style(style = cell_fill(color = "grey"), locations = cells_body(rows = seq(1, 1, 1))) %>%
tab_header(title = md("*Ride Statistics - Time*")) %>%
gtsave("images/gtsummary3.png")
sumtable %>%
select(elev_avg, elev_med, elev_min, elev_max) %>%
gt() %>%
cols_label(elev_avg = "Average", elev_med = "Median",
elev_min = "Lowest", elev_max = "Highest") %>%
cols_align(align = "center", columns = everything()) %>%
tab_style(style = cell_fill(color = "grey"), locations = cells_body(rows = seq(1, 1, 1))) %>%
tab_header(title = md("*Ride Statistics - Elevation (meters)*")) %>%
gtsave("images/gtsummary4.png")
sumtable %>%
select(cal_avg, cal_min, cal_max, kiloj_avg, kiloj_min, kiloj_max) %>%
gt() %>%
cols_label(cal_avg = "Average", cal_min = "Least", cal_max = "Most",
kiloj_avg = "Average", kiloj_min = "Least", kiloj_max = "Most") %>%
cols_align(align = "center", columns = everything()) %>%
tab_spanner(label = "Calories Burned", columns = c(cal_avg, cal_min, cal_max)) %>%
tab_spanner(label = "Kilojoules Burned", columns = c(kiloj_avg, kiloj_min, kiloj_max)) %>%
tab_style(style = cell_fill(color = "grey"), locations = cells_body(rows = seq(1, 1, 1))) %>%
tab_header(title = md("*Ride Statistics - Energy*")) %>%
gtsave("images/gtsummary5.png")
```
::: {.absolute top="80" left="10"}
![](images/gtsummary2.png)
:::
::: {.absolute top="335" left="10"}
![](images/gtsummary3.png)
:::
::: {.absolute top="595" left="10"}
![](images/gtsummary4.png)
:::
::: {.absolute top="840" left="10"}
![](images/gtsummary5.png)
:::
::: {.absolute top="80" left="900"}
- The rides spanned 1 km to 60 km, with the average & median ride around 4-5km, which makes sense given that my work commute was a bit over 4km and rides to Danish class were ~4km or ~6km depending on location.
<br>
<br>
- The elevation stats are what you’d expect for Denmark, and the average ride burned 140-150 units of energy.
:::
## Let's make some charts with `ggplot2`
```{r}
#| eval: false
#| echo: true
library(patchwork)
ridesplot1 <- rides_mth_type %>%
ggplot(aes(activity_month_abbv, rides_by_month)) +
geom_col(fill = "#C8102E") +
geom_text(aes(label= rides_by_month), color = "white", size = 5, vjust = 1.5) +
labs(x = "", y = "", title = "Spring & Summer Weather = More Rides",
subtitle = glue::glue("*Average Rides / Month = {round(mean(rides_mth_type$rides_by_month, 3))}*")) +
theme_minimal() +
theme(panel.grid = element_blank(), plot.title = element_text(hjust = 0.5),
plot.subtitle = element_markdown(hjust = 0.5),
axis.text.y = element_blank())
ridesplot2 <- rides_mth_type %>%
group_by(ride_type) %>%
mutate(rides_by_type = sum(ride_type_n)) %>%
ungroup() %>%
distinct(rides_by_type, .keep_all = TRUE) %>%
mutate(ride_type_pct = rides_by_type / sum(rides_by_type)) %>%
{. ->> tmp} %>%
ggplot(aes(ride_type, ride_type_pct)) +
geom_col(fill = "#C8102E") +
scale_x_discrete(labels = paste0(tmp$ride_type, "<br>Total Rides = ", tmp$rides_by_type, "")) +
geom_text(data = subset(tmp, ride_type != "Workout"),
aes(label= scales::percent(round(ride_type_pct, 2))), color = "white", size = 5, vjust = 1.5) +
geom_text(data = subset(tmp, ride_type == "Workout"),
aes(label= scales::percent(round(ride_type_pct, 2))), color = "#C8102E", size = 5, vjust = -.5) +
labs(x = "", y = "", title = "Lots of Riding to Work or Danish Class") +
theme_minimal() +
theme(panel.grid = element_blank(), plot.title = element_text(hjust = 0.5),
axis.text.y = element_blank(), axis.text.x = element_markdown())
rm(tmp)
ridesplot1 + ridesplot2
```
## Let's make some charts with `ggplot2`
![](images/chart1_month_type.png)
## Let's make some charts with `ggplot2`
```{r}
#| eval: false
#| echo: true
rides_mth_type %>%
ggplot(aes(activity_month_t, ride_type_pct, fill = ride_type)) +
geom_bar(stat = "identity") +
geom_text(data = subset(rides_mth_type, ride_type != "Workout"),
aes(label = scales::percent(round(ride_type_pct, 2))),
position = position_stack(vjust = 0.5), color= "white", vjust = 1, size = 5) +
labs(x = "", y = "", title = "Most Rides Each Month Were Commutes to/from Work or Danish Class") +
scale_fill_manual(values = c("#0072B2", "#E69F00", "#CC79A7"), labels = c("Commute/<br>Studieskolen", "Other", "Workout")) +
theme_minimal()+
theme(legend.position = "bottom", legend.spacing.x = unit(0, 'cm'),
legend.text = element_markdown(),
legend.key.width = unit(1.5, 'cm'), legend.title = element_blank(),
axis.text.y = element_blank(), plot.title = element_text(hjust = 0.5),
panel.grid.major = element_blank(), panel.grid.minor = element_blank()) +
guides(fill = guide_legend(label.position = "bottom"))
```