-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.Rmd
5330 lines (4568 loc) · 143 KB
/
index.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
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: "Pedalling Forward: The Evolution of Dedicated Cycling Infrastructure in Canadian Cities from 2010 to 2022"
subtitle: "R Code for Figures and Tables"
author:
- "Richard Wen richard.wen@utoronto.ca"
- "Konrad Samsel konrad.samsel@mail.utoronto.ca"
- "Brice Batomen brice.kuimi@utoronto.ca"
- "Linda Rothman linda.rothman@torontomu.ca"
date: "`r format(Sys.time(), '%B %d, %Y')`"
knit: |
(function(input_rmd, ...) {
rmarkdown::render(
input_rmd,
rmarkdown::html_document(
toc = TRUE,
toc_float = TRUE,
highlight = "zenburn",
code_folding = "hide",
self_contained = FALSE
),
output_dir = "../docs",
output_file = "index", ...)
})
---
```{r include = FALSE, echo = FALSE}
knitr::opts_chunk$set(
warning = FALSE,
message = FALSE
)
```
**NOTE: Please allow ~30 seconds for the page to load completely.**
# Installation
1. Install [R](https://www.r-project.org/)
2. Install [RTools](https://cran.r-project.org/) if you are on Windows
3. Install [RStudio](https://posit.co/download/rstudio-desktop/)
For more details, see [Software and Package Versions](#software-and-package-versions).
# Running This Code
1. Ensure the installation steps above are completed
2. Download a zip of the code and data [here](https://github.com/rrwen/recovr-infracycle/archive/refs/heads/main.zip) and unzip it
* Code Repository: [github.com/rrwen/recovr-infracycle](https://github.com/rrwen/recovr-infracycle)
3. In RStudio, open the [src/src.Rproj](https://github.com/rrwen/recovr-infracycle/blob/main/src/src.Rproj) file
4. Then, open the [src/index.Rmd](https://github.com/rrwen/recovr-infracycle/blob/main/src/index.Rmd) file
6. In RStudio:
* Run all code: Click the `Run` drop down (top right of the code pane) and click `Run All`
* Generate HTML version: Click `knit` (top left of code pane) and a file will be generated in `docs/index.html` (you may have to try a couple times to succeed due to `webshot2` timeouts)
# Libraries
Install R packages if needed.
```{r warning = FALSE, message = FALSE, results = FALSE}
# Required packages
required_packages <- c(
"rmarkdown",
"bookdown",
"knitr",
"tidyverse",
"glue",
"readxl",
"ggtext",
"scales",
"patchwork",
"DiagrammeR",
"DiagrammeRsvg",
"webshot2",
"magick",
"rsvg",
"sf",
"tmap",
"ggspatial",
"prettymapr",
"units",
"lubridate",
"kableExtra",
"DT"
)
# Try to install packages if not installed
default_options <- options()
tryCatch(
{
# Disable interactivity
options(install.packages.compile.from.source = "always")
# Install package if not installed
for (package in required_packages) {
is_package_installed <- require(package, character.only = TRUE)
if (!is_package_installed & package != "osmplotr") {
cat(paste0("Installing package: ", package, "\n"))
install.packages(package)
} else {
cat(paste0("Package already installed: ", package, "\n"))
}
}
},
error = function(cond) {
stop(cond)
},
finally = {
options(default_options) # reset interactivity
}
)
```
Load R libraries.
```{r warning = FALSE, message = FALSE}
library(DiagrammeR)
library(DiagrammeRsvg)
library(ggtext)
library(glue)
library(kableExtra)
library(lubridate)
library(patchwork)
library(readxl)
library(rsvg)
library(sf)
library(tidyverse)
library(tmap)
library(ggspatial)
library(units)
```
# Settings
```{r}
settings <- list()
# Infrastructure types in order
settings$type_recode_infra <- c(
PBL = "Cycle Track",
BUF = "Buffered Lane",
PL = "Painted Lane",
LSB = "Local Street\nBikeway"
)
# Infrastructure types to remove
settings$type_filter_infra <- c("N", "None", "SR")
# Road types in order
settings$type_recode_road <- c(
Arterial = "Arterial",
Collector = "Collector",
Local = "Local"
)
# Column references
settings$year_col_road <- "verify_install_year"
settings$type_col_road <- "road_type_recode"
settings$type_col_infra <- "verify_install_type"
# Set years of interest
settings$year_min <- 2009
settings$year_max <- 2022
# Plot settings
settings$line_year <- 2019
settings$basemaps <- c(
"CartoDB.Positron",
"CartoDB.DarkMatter",
"Esri.WorldGrayCanvas"
)
# Map infrastructure changes since year
settings$infra_changes_year <- 2020
# Apply map settings
tmap_options(basemaps = settings$basemaps)
```
# Functions
## Function 0: datatable
Modify the default `datatable` function from `DT` library to generate interactive tables:
```{r}
datatable <- function(...) {
# Build arg list
args <- list(...)
# Default custom filename
filename <- if (!"filename" %in% names(args)) "data" else args$filename
args[["filename"]] <- NULL
# Add default extensions
args$extensions <- if (!"extensions" %in% names(args)) "Buttons" else args$extensions
# Add default args
args$filter <- if (!"filter" %in% names(args)) "top" else args$filter
args$fillContainer <- if (!"fillContainer" %in% names(args)) T else args$fillContainer
# Add default options
if (!"options" %in% names(args)) {
args$options <- list(
scrollY = "350px",
buttons = list(
list(
extend = "csv",
filename = filename,
exportOptions = list(columns = ":not(.rownames)")
),
list(
extend = "excel",
filename = filename,
exportOptions = list(columns = ":not(.rownames)"),
title = ""
)
),
columnDefs = list(
list(
targets = 0,
className = "rownames"
)
),
dom = "Bfrtip"
)
}
return(do.call(DT::datatable, args))
}
```
## Function 1: calc_yearly_len
Calculate yearly road lengths.
The following function calculates yearly road lengths by infrastructure type using cumulative sums and filling in missing years and types.
For a given infrastructure type, the total road length for a given year is expressed below:
$$
length_{year,type} = f(year,type) = \sum_{i=year_{min}}^{year}l_{i, type}\ \mid\ l_{i, type} \geq 0
$$
Where:
- $year$ is the given year
- $type$ is the infrastructure type
- $year_{min}$ is the earliest year available in the data
- $l_{i,type}$ is the road length $l$ for previous years $i$ and infrastructure $j$
- $l_{i,type}$ is set to 0 if there is no data
```{r}
#' Calculate Yearly Road Lengths By Infrastructure Type
#'
#' Calculates the cumulative yearly road lengths by infrastructure type without considering infrastructure changes.
#'
#' @param df A data.frame with three columns containing the year, type, and road lengths.
#' @param year_col The name (char) or index (int) of the column containing the years.
#' @param type_col The name (char) or index (int) of the column containing the infrastructure type
#' @param len_col The name (char) or index (int) of the column containing the road lengths.
#' @param out_col The name (char) of the column containing the calculated yearly road lengths by type.
#'
#' @return A data.frame with three columns containing the year, type, and calculated yearly road lengths by type.
#' @export
#'
calc_yearly_len <- function(
df,
year_col = "verify_install_year",
type_col = "verify_install_type",
len_col = "geometry_len_km",
out_col = "len",
year_min = settings$year_min,
year_max = settings$year_max
) {
# Convert data types
df <- as.data.frame(df)
df[[year_col]] <- as.integer(df[[year_col]])
df[[type_col]] <- as.character(df[[type_col]])
df[[len_col]] <- as.numeric(df[[len_col]])
# Remove rows with empty type
out <- df %>% filter(
!is.na(.data[[type_col]])
)
# Filter to min and max years
if (year_min > 0) {
df <- df %>% filter(
.data[[year_col]] >= year_min
)
} else {
year_min <- min(out[[year_col]], na.rm = TRUE)
}
if (year_max > 0) {
df <- df %>% filter(
.data[[year_col]] <= year_max
)
} else {
year_max <- max(out[[year_col]], na.rm = TRUE)
}
# Add dummy len for each type and year combo
# Covers cases where type and year combo does not exist
# E.g. No new PL installs in 2021, hence a record PL in 2021 does not exist
type_uniq <- unique(out[[type_col]])
type_n <- length(type_uniq)
year_uniq <- year_min:year_max
year_n <- length(year_uniq)
out <- out %>% add_row(
!!year_col := rep(year_uniq, each = type_n),
!!type_col := rep(type_uniq, year_n),
!!len_col := rep(0, type_n * year_n)
)
# Calc cumsum for each non-empty type ordered by year
out <- out %>%
arrange(.data[[year_col]]) %>%
group_by(.data[[type_col]]) %>%
mutate(
!!out_col := cumsum(.data[[len_col]])
)
# Get the last cumsum for each year and type
out <- out %>%
group_by(.data[[year_col]], .data[[type_col]]) %>%
arrange(desc(row_number())) %>%
slice(1)
# Return only the columns spec
out <- out %>% select(c(
year_col,
type_col,
out_col
))
return(out)
}
```
## Function 2: calc_yearly_adj_len
Calculate yearly adjusted road length.
The following function calculates yearly adjusted road lengths by infrastructure type using cumulative sums and filling in missing years and types.
For a given infrastructure type, the total adjusted road length for a given year is expressed below:
$$
length_{year,type}^{install} + length_{year,type}^{change_i} - length_{year,type}^{replacement_i}
$$ Where:
- $length_{year,type}^{install}$ are the yearly cumulative road lengths for an infrastructure $type$ installation
- $length_{year,type}^{change_i}$ are the yearly cumulative road lengths for an infrastructure $type$ change in order $i$
- $length_{year,type}^{replacement_i}$ are the yearly cumulative road lengths for an infrastructure $type$ replaced by change in order $i$
```{r}
#' Calculate Yearly Adjusted Road Lengths By Infrastructure Type
#'
#' Calculates the cumulative yearly adjusted road lengths by infrastructure type accounting for installations and subsequent changes.
#'
#' @param df A data.frame with three columns containing the year, type, and road lengths.
#' @param year_cols A vector of the names (char) or indices (int) of the columns containing the years of installations followed by infrastructure changes in order.
#' @param type_cols A vector of the names (char) or indices (int) of the columns containing the infrastructure types of installations followed by infrastructure changes in order.
#' @param type_col The name (char) of the column containing the type.
#' @param len_cols A vector of the names (char) or indices (int) of the columns containing the road lengths of installations followed by infrastructure changes in order.
#' @param out_cols The name (char) of the column containing the calculated yearly road lengths by type.
#' @param out_col The name (char) of the column containing the calculated yearly adjusted road lengths by type.
#' @param repl_suffix A suffix (char) to append to the columns representing the road lengths of replaced infrastructure types from changes.
#' @param ... Additional arguments passed to calc_yearly_len.
#'
#' @return A data.frame with columns containing the year, type, cumulative road lengths of installations, changes, and replacements, and calculated yearly adjusted road lengths by type.
#' @export
#'
calc_yearly_adj_len <- function(
df,
year_cols = c("verify_install_year", "verify_upgrade1_year", "verify_upgrade2_year"),
type_cols = c("verify_install_type", "verify_upgrade1_type", "verify_upgrade2_type"),
type_col = "type",
len_cols = "geometry_len_km",
out_cols = c("install_len", "upgrade1_len", "upgrade2_len"),
out_col = "adj_len",
repl_suffix = "_replaced",
...
) {
# Ensure df
df <- as.data.frame(df)
# Convert len_col if char
len_cols <- rep(len_cols, length(year_cols))
# Check cols same size
year_cols_n <- length(year_cols)
type_cols_n <- length(type_cols)
len_cols_n <- length(len_cols)
out_cols_n <- length(out_cols)
if (length(unique(c(year_cols_n, type_cols_n, len_cols_n, out_cols_n))) != 1) {
stop(glue(
"The arguments 'year_cols' ({year_cols_n}), 'type_cols' ({type_cols_n}), 'len_cols' ({len_cols_n}), and 'out_cols' ({out_cols_n}) must be the same length."
))
}
# Calc yearly lens by infra type per install or change
out <- list()
for (i in 1:length(year_cols)) {
# Get year, type, and len cols
ycol <- year_cols[[i]]
tcol <- type_cols[[i]]
lcol <- len_cols[[i]]
ocol <- out_cols[[i]]
# Calc yearly len for install or change
has_infra <- !is.na(df[[tcol]]) %>% all
if (has_infra) {
out <- append(
out,
calc_yearly_len(
df,
year_col = ycol,
type_col = tcol,
len_col = lcol,
out_col = ocol,
...
) %>%
rename(
"year" := !!ycol,
"type" := !!tcol
) %>% list
)
}
# Calc yearly len for replacement
if (i > 1) {
# Get repl cols
tcol_repl <- type_cols[[i - 1]]
lcol_repl <- len_cols[[i - 1]]
# Filter for repl records only where type is not eq to change type
df_repl <- df %>% filter(.data[[tcol]] != .data[[tcol_repl]])
# Calc repl len if there are any changes
has_change <- !is.na(df_repl[[tcol]]) %>% all
if (has_change) {
out <- append(
out,
calc_yearly_len(
df_repl,
year_col = ycol,
type_col = tcol_repl,
len_col = lcol_repl,
out_col = glue("{ocol}{repl_suffix}"),
...
) %>%
rename(
"year" := !!ycol,
"type" := !!tcol_repl
) %>% list
)
}
}
}
# Combine all lens in list to single df
out <- out %>%
reduce(
left_join, by = c("year", "type")
) %>%
ungroup()
# Create template for change and repl cols
change_cols <- paste0(out_cols[2:out_cols_n])# change cols
change_cols <- c(change_cols, paste0(out_cols[2:out_cols_n], repl_suffix)) # repl cols
change_cols_add <- rep(0, length(change_cols)) # set default vals
names(change_cols_add) <- change_cols
# Add change and repl cols set to 0 if not present
out <- out %>% add_column(
!!!change_cols_add[setdiff(names(change_cols_add), names(.))]
)
# Set NA to 0
out <- out %>% mutate(
across(everything(), ~replace_na(., 0))
)
# Calc yearly adj lens by infra type
out <- out %>%
mutate( # added len by infra types due to install or changes
!!out_col := reduce(across(all_of(out_cols)), `+`)
) %>%
mutate( # removed len by infra types due to replacements
!!out_col := .data[[out_col]] - reduce(
across(all_of(
paste0(out_cols[2:out_cols_n], repl_suffix)
)),
`-`
)
)
# Rename type col
out <- out %>% rename(!!type_col := type)
return(out)
}
```
## Function 3: plot_yearly_len
Plot road lengths by generic types.
This function plots an area chart showing the cumulative road lengths by a user-defined type for each year.
This is a generic function for user-defined types such as infrastructure or road types.
```{r}
#' Plot Yearly Road Lengths By Type
#'
#' Creates an area plot of road lengths by category types.
#'
#' @param df A data.frame with three columns containing the year, type, and road lengths.
#' @param title The title (char) of the plot.
#' @param title_underline Set to TRUE to underline the title.
#' @param x_title The title (char) of the x-axis.
#' @param y_title The title (char) of the y-axis.
#' @param y_suffix The suffix (char) to add to the end of y axis values.
#' @param y_lim Minimum and maximum road length (numeric) as a vector of length 2 to limit the range of the y-axis. Set to `NULL` for auto.
#' @param legend_title The title (char) of the legend.
#' @param legend Set to TRUE to include a legend.
#' @param year_col The name (char) or index (int) of the column containing the years.
#' @param year_min The minimum year (int) to display.
#' @param year_max The maximum year (int) to display.
#' @param year_int The year intervals (int) to display. For example, 1 displays every year, and 2 displays every two years.
#' @param len_col The name (char) or index (int) of the column containing the road lengths.
#' @param len_per_start Set to `TRUE` to add final percentages at the starting year or `FALSE` to omit this.
#' @param len_per_end Set to `TRUE` to add final percentages at the ending year or `FALSE` to omit this.
#' @param type_col The name (char) or index (int) of the column containing the type.
#' @param type_filter A vector (char) of types to remove fomr the plot.
#' @param type_recode A named vector (char) of names representing types and values representing the values to replace each type with.
#' @param line_km The km (numeric) of the red reference line.
#' @param line_show Set to TRUE to draw the km red reference line.
#' @param line_year Set to a year (int) to draw a reference line for a year. If FALSE, a line will not be drawn.
#' @param color_low The bottom color (char) of the type.
#' @param color_high The top color (char) of the type.
#' @param color_manual A set of manual colors to use for the areas. The default `NULL` uses `color_low` and `color_high` instead.
#' @return An area ggplot of the cumulative yearly road lengths by type.
#' @export
#'
plot_yearly_len <- function(
df,
title = "",
title_underline = TRUE,
x_title = "",
y_title = "",
y_suffix = " km",
y_lim = NULL,
legend_title = "Type",
legend = TRUE,
year_col = "year",
year_min = FALSE,
year_max = FALSE,
year_int = 1,
len_col = "adj_len",
len_per_start = FALSE,
len_per_end = FALSE,
type_col = "type",
type_filter = c(),
type_recode = c(),
line_km = 10,
line_show = FALSE,
line_year = FALSE,
color_low = "#DFEBF7",
color_high = "#3683BB",
color_manual = NULL
) {
# Filter to start and end years
if (year_min > 0) {
df <- df %>% filter(
.data[[year_col]] >= year_min
)
}
if (year_max > 0) {
df <- df %>% filter(
.data[[year_col]] <= year_max
)
}
# Filter out particular infrastructure types
if (length(type_filter) > 0) {
df <- df %>% filter(
!.data[[type_col]] %in% type_filter
)
}
# Recode and reorder category types
if (length(type_recode) > 0) {
# Reorder category types
type_uniq <- unique(df[[type_col]])
type_reorder <- names(type_recode)
type_reorder <- c(type_reorder, type_uniq[!type_uniq %in% type_reorder])
df[[type_col]] <- factor(df[[type_col]], levels = type_reorder)
# Recode category types
df[[type_col]] <- recode(df[[type_col]], !!!type_recode)
}
# Create fill colors
type_n <- length(type_uniq)
if (is.null(color_manual)) {
type_colors <- scales::seq_gradient_pal(
color_low,
color_high
)(seq(0, 1, length.out = type_n))
} else {
type_colors <- color_manual
}
# Create base area plot with legend and labels
len_max <- max(df[[len_col]], na.rm = TRUE)
year_max <- max(df[[year_col]], na.rm = TRUE)
out <- ggplot(
df,
aes(
x = .data[[year_col]],
y = .data[[len_col]],
fill = .data[[type_col]],
order = desc(.data[[type_col]])
)
) +
geom_area(colour = NA, alpha = 0.7) +
scale_fill_manual(values = type_colors) +
geom_line(
position = "stack",
size = 0.2
) +
labs(
x = x_title,
y = y_title,
fill = legend_title
) +
guides(
fill = FALSE,
color = FALSE
) +
scale_x_continuous(
breaks = seq(year_min, year_max, by = year_int),
labels = seq(year_min, year_max, by = year_int),
limits = c(if (len_per_start) year_min - 1 else year_min, if (len_per_end) year_max + 1 else year_max)
) +
scale_y_continuous(
label = scales::label_number(suffix = y_suffix)
) +
theme_minimal() +
theme(
plot.margin = unit(c(5,5,5,5), "points")
)
# Scale road length axis y
if (!is.null(y_lim)) {
out <- out + ylim(y_lim)
}
# Add title
if (title_underline) {
out <- out + ggtitle(
bquote(underline(.(title)))
)
} else {
out <- out + ggtitle(title)
}
# Add legend
if (legend) {
out <- out + guides(fill = guide_legend(
reverse = FALSE,
override.aes = list(
alpha = 0.7,
color = NA,
shape = NA
)
))
}
# Add percentages to start
if (len_per_start) {
df_perc_start <- df %>% filter(
.data[[year_col]] == year_min
) %>% arrange(desc(.data[[type_col]])) %>% mutate(
len = cumsum(.data[[len_col]]) - (.data[[len_col]] / 2),
perc = .data[[len_col]] / sum(.data[[len_col]], na.rm = T)
) %>% filter(
perc > 0
) %>% mutate(
perc = paste0(round(perc * 100, 1), "%")
)
out <- out + geom_text(
data = df_perc_start,
x = year_min,
size = 2.75,
hjust = 1.225,
aes(
y = len,
label = perc
)
)
}
# Add percentages to end
if (len_per_end) {
df_perc_end <- df %>% filter(
.data[[year_col]] == year_max
) %>% arrange(desc(.data[[type_col]])) %>% mutate(
len = cumsum(.data[[len_col]]) - (.data[[len_col]] / 2),
perc = .data[[len_col]] / sum(.data[[len_col]], na.rm = T),
) %>% filter(
perc > 0
) %>% mutate(
perc = paste0(round(perc * 100, 1), "%")
)
out <- out + geom_text(
data = df_perc_end,
x = year_max,
size = 2.75,
hjust = -0.225,
aes(
y = len,
label = perc
)
)
}
# Add dotted year ref line
if (line_year) {
out <- out + geom_vline(
xintercept = line_year,
color = "black",
linetype = "dashed"
)
}
# Add red 50km ref line
if (line_show) {
out <- out + geom_segment( # 50km red line
aes(
x = 2009,
y = 0,
xend = 2009,
yend = line_km,
color = "#bb0000"
)
) +
geom_segment( # 50km red triangle point down
aes(
x = 2009,
y = (line_km + 0.01) - (len_max * 0.05),
xend = 2009,
yend = line_km - (len_max * 0.05),
color = "#bb0000"
),
arrow = arrow(
length = unit(0.03, "npc"),
ends = "last",
type = "closed"
)
) +
geom_segment( # 50km red triangle point up
aes(
x = 2009,
y = (len_max * 0.05) - 0.01,
xend = 2009,
yend = (len_max * 0.05),
color = "#bb0000"
),
arrow = arrow(
length = unit(0.03, "npc"),
ends = "last",
type = "closed"
)
) +
annotate(
"text",
x = 2009,
y = line_km,
label = paste0(line_km, "km"),
color = "#bb0000",
hjust = -0.225
)
}
return(out)
}
```
## Function 3a: plot_yearly_len_infra
Plot yearly adjusted road lengths by infrastructure type.
This function plots area charts of yearly road lengths by infrastructure types for a list of data.
This uses the `plot_yearly_len` function.
```{r}
#' Plot Yearly Road Lengths By Infrastructure Type
#'
#' Creates area plots of road lengths by infrastructure type.
#'
#' @param df_list A list of lists, where each key is the title and each value contains a list with the following structure:
#' \itemize{
#' \item \code{data}: data.frame containing the install and change years, type, and road segment lengths.
#' \item \code{roadway_total}: the total roadway length if `rodway_per` is given. This is used as the denominator to normalize road lengths.
#' \item \code{roadway_per}: Number of units of total roadway length (numeric) to normalize by (e.g. 1000 means per 1000 km of roadway). Set to `NULL` or omit to disable normalization of road lengths.
#' \item \code{color_manual}: Optional color of the area polygons to be set manually.
#' }
#' @param len_title The title (char) for the road lengths.
#' @param line_show Set to `TRUE` to add a 50km reference line.
#' @param ... Additional arguments passed to `plot_yearly_len`.
#'
#' @return Multiple area ggplots of the cumulative yearly road lengths by infrastructure type combined with patchwork.
#' @export
#'
plot_yearly_len_infra <- function(
df_list,
len_title = "Total length per 1000 centreline-km of roadway",
line_km = 10,
line_show = TRUE,
...
) {
# Create infra plots from data
p <- list()
pdata <- list()
for (i in 1:length(df_list)) {
# Get data and plot title
df <- df_list[[i]]$data
ptitle <- names(df_list)[[i]]
# Get roadway vars if exists
roadway_per <- NULL
roadway_total <- NULL
if ("roadway_per" %in% names(df_list[[i]])) {
roadway_per <- df_list[[i]]$roadway_per
}
if ("roadway_total" %in% names(df_list[[i]])) {
roadway_total <- df_list[[i]]$roadway_total
}
# Calc infra per year
p[[i]] <- calc_yearly_adj_len(
df,
type_col = settings$type_col_infra
)
# Norm len if needed
len_col <- "adj_len"
if (!is.null(roadway_per)) {
p[[i]] <- p[[i]] %>% mutate(
adj_len_norm =
(adj_len / roadway_total) * roadway_per
)
len_col = "adj_len_norm"
}
# Add infra data
pdata[[i]] <- p[[i]] %>%
mutate(title = ptitle) %>%
select(
title,
year,
adj_len,
adj_len_norm,
everything()
)
# Add infra plot
p[[i]] <- pdata[[i]] %>% plot_yearly_len(
title = ptitle,
year_min = settings$year_min,
year_max = settings$year_max,
type_col = settings$type_col_infra,
type_filter = settings$type_filter_infra,
type_recode = settings$type_recode_infra,
legend_title = "Infrastructure Type",
line_km = line_km,
line_show = line_show,
line_year = settings$line_year,
len_col = len_col,
color_manual = df_list[[i]]$color_manual,
...
)
}
# Y-axis title
y_title <- ggplot() +
annotate(
geom = "text",
x = 1,
y = 1,
label = len_title,
angle = 90,
size = 5
) +
coord_cartesian(clip = "off")+
theme_void()
# Combine all infra plots together
out <- list()
out$data <- pdata %>% bind_rows
out$plot <- (y_title | wrap_plots(p, nrow = length(p))) +
plot_annotation(
title = "Roadways with Dedicated Cycling Infrastructure",
caption = sprintf("Years (%s-%s)", settings$year_min, settings$year_max),
theme = theme(
plot.title = element_text(hjust = 0.5, size = 16),
plot.caption = element_text(hjust = 0.5, size = 14)
)
) +
plot_layout(widths = c(0.05, 1))
return(out)
}
```
## Function 3b: plot_yearly_len_road
Plots yearly adjusted road lengths for road types.
This function plots area charts of yearly road lengths by overall road type and by infrastructure separated by each road type.
This uses the `plot_yearly_len` function.
```{r}
#' Plot Yearly Road Lengths By Road Type
#'
#' Creates area plots of road lengths by overall road type, and by infrastructure per road type.
#'
#' @param df The data.frame containing the install and change years, type, and road segment types and lengths.
#' @return Multiple area ggplots of the cumulative yearly road lengths by road type combined with patchwork.
#' @export
#'
plot_yearly_len_road <- function(df, title = "Roadways with Dedicated Cycling Infrastructure") {
# Create list to store plots and data
p <- list()
pdata <- list()
# Format plot data
pdata[[1]] <- calc_yearly_len(
df,
year_col = settings$year_col_road,
type_col = settings$type_col_road
) %>% mutate(
road_type = "All"
)
# Plot overall road types
p[[1]] <- pdata[[1]] %>%
plot_yearly_len(
title = title,
title_underline = FALSE,
year_col = settings$year_col_road,
year_min = settings$year_min,
year_max = settings$year_max,
x_title = sprintf("Years (%s-%s)", settings$year_min, settings$year_max),
y_title = "Total Length (Centreline km)",
legend_title = "Roadway Type",
type_col = settings$type_col_road,
type_recode = settings$type_recode_road,
len_col = "len",
line_show = FALSE,
line_year = settings$line_year,
color_low = "#C1DDB3",
color_high = "#297A22"
) +
theme(
plot.title = element_text(size = 18),
plot.margin = margin(0, 0, 0, 0, "pt")
)
# Plot arterial, collector, and local road by infra
rtypes <- c("Arterial", "Collector", "Local")
for (i in 1:length(rtypes)) {
# Get road type
r <- rtypes[i]
# Format infra data for road type
pdata[[i + 1]] <- calc_yearly_adj_len(
df %>% filter(.data[[settings$type_col_road]] == r),
type_col = settings$type_col_infra
) %>%
mutate(
road_type = r
)