-
Notifications
You must be signed in to change notification settings - Fork 0
/
leaflet_tutorial.Rmd
709 lines (474 loc) · 15.6 KB
/
leaflet_tutorial.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
---
title: "Leaflet Maps"
author: "Insert Name"
date: "27/11/2021"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, warning = FALSE, message = FALSE)
```
# Package Installation
```{r}
# Use install.packages("package name") to install any of the packages below
# To install the rgeoboundaries package you will need to run the following two lines of code
# install.packages("remotes")
# remotes::install_gitlab("dickoa/rgeoboundaries")
library(tidyverse) ## For plotting and data wrangling.
library(leaflet) ## For leaflet interactive maps
library(sf) ## For spatial data
library(RColorBrewer) ## For colour palettes
library(htmltools) ## For html
library(leafsync) ## For placing plots side by side
library(kableExtra) ## Table output
library(stringr) ## String manipulation
library(rgeoboundaries) ## Administrative boundaries
```
# Birth Rates in North Carolina
* We will use the North Carolina (`nc`) data from the `sf` package.
* Let's load in the data for North Carolina using the function `st_read`.
```{r nc-data, eval = TRUE, messages = FALSE}
nc_df <- st_read(system.file("shape/nc.shp", package="sf"))
```
* `st` = spatial type and `.shp` is a common shape file format (e.g. GIS).
## Rename the columns and view the data North Carolina
* Number of births for counties in North Carolina in 1974
* Rename our columns to country, births, and geometry.
```{r nc-data2, eval = TRUE, messages = FALSE}
nc <- nc_df %>%
select("NAME", "BIR74", "BIR79", "geometry") %>%
rename("county" = "NAME", "births1974" = "BIR74", "births1979" = "BIR79")
```
## Let's inspect the data
* Let's load in the data for North Carolina (nc)
```{r nc-view, eval = TRUE}
head(nc)
```
## And inspect the structure
```{r nc-str, eval = TRUE}
str(nc)
```
## Building a map in ggplot2
```{r first-map1a, eval=TRUE}
ggplot(nc) #<<
```
```{r first-map1e, eval=TRUE}
ggplot(nc) +
geom_sf(aes(fill = births1974)) +
labs(title = "Births per county in 1974",
x = "Longitude",
y = "Latitude",
fill = "Births") +
scale_y_continuous(breaks = 34:36) #<<
```
## Accessing Administrative Boundaries
```{r access admin 0 boundaries, fig.alt="Map of Nigeria"}
# One country
nigeria <- geoboundaries(country = "Nigeria") #<<
ggplot(data = nigeria) +
geom_sf()
```
```{r access admin 0 boundareis for nigeria and chad, fig.alt="Map of Nigeria and Chad: admin level 0."}
# Two countries
nigeria_chad <- geoboundaries(country = c("Nigeria", "Chad")) #<<
ggplot(data = nigeria_chad) +
geom_sf()
```
```{r access admin level 1 boundaries, fig.alt="Map of Nigeria: admin level 1."}
# Admin Level 1
nigeria <- geoboundaries(country = "Nigeria",
adm_lvl = "adm1") #<<
ggplot(data = nigeria) +
geom_sf()
```
`r icons::icon_style(icons::fontawesome("lightbulb", style = "solid"), scale = 1)` Find out more administrative boundaries and other open data sources tutorials at [rspatialdata.github.io](https://rspatialdata.github.io)
```{r View Nigeria data}
nigeria %>%
kableExtra::kable()
```
### Joining spreadsheet data to spatial data
* Let's say we have population data we want to match.
```{r nigeria-pop}
# Two countries
nigeria_pop <- read_csv(file = "data/nga_admpop_adm1_2020.csv") #<<
head(nigeria_pop)
```
`r icons::icon_style(icons::fontawesome("lightbulb", style = "solid"), scale = 2)` In what column do we find spatial information we can use to match this data to the other dataset?
* We can match the data based on the names of the administrative boundaries.
```{r nigeria-pop-spatial-join}
# Joining Nigeria spatial data to the population data by the admin name columns
nigeria_pop <- nigeria_pop %>%
mutate(ADM1_NAME = str_to_title(ADM1_NAME, locale = "en"))
# how well do they match up?
anti_join(x = nigeria,
y = nigeria_pop,
by = c("shapeName" = "ADM1_NAME"))
```
Often one of the trickiest part is to get the spelling of regions to match up. We can check where mismatches occur with an `anti_join`. The NA here is from Akwa Lbom and Akwa lbom.
* We can fix mismatches using `case_when`
```{r nigeria-pop-spatial-join-2}
# Joining Nigeria spatial data to the population data by the administrative data column
nigeria_pop <- nigeria_pop %>%
mutate(ADM1_NAME = str_to_title(ADM1_NAME, locale = "en"),
ADM1_NAME_SC = case_when(ADM1_NAME == "Akwa Ibom" ~ "Akwa lbom",
TRUE ~ ADM1_NAME))
nigeria_df <- left_join(x = nigeria,
y = nigeria_pop,
by = c("shapeName" = "ADM1_NAME_SC"))
```
`r icons::icon_style(icons::fontawesome("info-circle", style = "solid"), scale = 1)` We can use `case_when` to change the name to match.
* Now we can create our map
```{r first-nigeria-map3, fig.alt="Map of Nigeria with admin 1 areas filled by population"}
ggplot(data = nigeria_df) +
geom_sf(aes(fill = T_TL)) +
labs(x = "Longitude",
y = "Latitude",
fill = "Total Population")
```
## Coordinate reference system
* Every location on earth is specified by a longitude and latitude.
* The Coordinate Reference system (CRS) determines how the data will be projected onto a map.
* We can check the CRS using `st_crs`:
```{r checking the CRS}
st_crs(nc)
```
* The CRS is specified in the attributes `epsg` and `proj4string`.
```{r checking the CRS Nigeria, eval = FALSE}
### Fill in the blank to check the nigeria data set
st_crs(____)
```
## Transforming coordinate reference system
* You can transform a coordinate reference system using the `st_transform()`.
* But what is a sensible coordinate reference system to assign?
* Well, a good place to start is with the one that leaflet uses for plotting the world: EPSG 4326.
```{r changing the CRS using st_transform}
nc <- st_transform(nc, "+init=epsg:4326")
st_crs(nc)
```
```{r changing the CRS using st_transform nigeria, eval = FALSE}
## Fill in the blanks for the nigeria dataset
nigeria_df <- st_transform(nigeria_df, "+init=epsg:4326")
______(nc)
```
# Our first leaflet map
* Every plot starts with `leaflet()`
```{r first-leaflet-map1a, eval=TRUE}
leaflet(data = nc)
```
* Layers are added using `%>%`
```{r first-leaflet-map1b, eval=TRUE}
leaflet(data = nc) %>%
addTiles() #<<
```
* N.B. Layers are added with `%>%` in `leaflet` and `+` in `ggplot`. `%>%` also is used in the `tidyverse` packages.
* We can set the view using `setView()`
```{r first-leaflet-map1c, eval=TRUE}
leaflet(data = nc) %>%
addTiles() %>%
setView(lng = -80, #<<
lat = 34.5, #<<
zoom = 5) #<<
```
* Add different background map using addProviderTiles
```{r first-leaflet-map1d, eval=TRUE}
leaflet(data = nc) %>%
addProviderTiles(providers$Esri.OceanBasemap) %>%
setView(lng = -80,
lat = 34.5,
zoom = 5)
```
* N.B. The different provider tiles come with different licensing.
* Add polygons using `addPolygons()`
```{r first-leaflet-map1e, eval=TRUE}
leaflet(data = nc) %>%
addProviderTiles(providers$Stamen.Terrain) %>%
setView(lng = -80,
lat = 34.5,
zoom = 5) %>%
addPolygons() #<<
```
* Fill in the blanks to create a leaflet map with the Nigeria data. What longitude and latitude do you want to set the view with?
```{r nigeria-first-leaflet, eval = FALSE}
leaflet(data = ) %>%
addProviderTiles(providers$Stamen.Terrain) %>%
setView(lng = _____,
lat = _____,
zoom = 5) %>%
addPolygons() #<<
```
## Creating a colour palette
* What type of data are we showing?
* Who is our audience?
* Tools
* [ColorBrewer2.org](https://colorbrewer2.org/#type=sequential&scheme=BuGn&n=3)
* [Color Picker](https://www.colorcodepicker.com/)
## Creating a colour palette
* `RColorBrewer` includes **sequential** colour palettes (e.g. number of people).
```{r pal-sequential, eval = TRUE}
display.brewer.all(type = "seq")
```
## Creating a colour palette
* `RColorBrewer` includes **diverging** colour palettes (e.g. to show distinct categories).
```{r pal-diverging, eval = TRUE}
display.brewer.all(type = "div")
```
* First we will define the colour palette and bins for the plot.
```{r Defining colour bins, eval = TRUE}
summary(nc$births1974)
summary(nc$births1979)
bins <- seq(0, 35000, 5000)
```
* Then we can define the colours for the palette:
```{r Defining the palette, eval = TRUE}
pal74 <- colorBin("OrRd", domain = nc$births1974, bins = bins)
pal79 <- colorBin("OrRd", domain = nc$births1979, bins = bins)
```
* What might make sense as bins for showing our Nigeria population?
```{r bins for nigeria plot, eval = FALSE}
summary(nigeria_df$TL)
bins <- seq(from = ___, to = ____, by = ____)
pal <- colorBin("OrRd", domain = ________, bins = bins)
```
* Customising `addPolygons()`
```{r first-leaflet-map1f, eval=TRUE}
leaflet(data = nc) %>%
addProviderTiles(providers$Stamen.Terrain) %>%
setView(lng = -80,
lat = 34.5,
zoom = 6) %>%
addPolygons(
fillColor = ~pal74(nc$births1974),
fillOpacity = 0.7, #<<
color = "white", #<<
opacity = 1, #<<
weight = 2 #<<
)
```
```{r nigeria leaflet 2, eval = FALSE}
# Try further customizing your Nigeria plot
leaflet(data = ) %>%
addProviderTiles(providers$Stamen.Terrain) %>%
setView(lng = _____,
lat = _____,
zoom = 5) %>%
addPolygons(
fillColor = ~pal(_______),
fillOpacity = 0.7, #<<
color = "white", #<<
opacity = 1, #<<
weight = 2 #<<
) #<<
```
* Customising `addPolygons()`
```{r first-leaflet-map1g, eval=TRUE}
leaflet(data = nc) %>%
addProviderTiles(providers$Stamen.Terrain) %>%
setView(lng = -80,
lat = 34.5,
zoom = 6) %>%
addPolygons(
fillColor = ~pal74(nc$births1974), #<<
fillOpacity = 1, #<<
color = "blue", #<<
opacity = 0.7, #<<
weight = 1 #<<
)
```
# What can you customise in addPolygons()
```{r what can you customise with addPolygons, eval = FALSE}
?addPolygons()
```
* `color:` stroke color
* `weight:` stroke width in pixels
* `opacity:` stroke opacity
* `fillColor:` fill color
* `fillOpacity:` fill opacity
* `highlightOptions:` Options for highlighting the shape on mouse over.
* Let's assign our plot to an object.
```{r first-leaflet-map1h, eval=TRUE}
m1 <- leaflet(data = nc) %>% #<<
addProviderTiles(providers$Stamen.Terrain) %>%
setView(lng = -80,
lat = 34.5,
zoom = 6)
m1 %>%
addPolygons(
fillColor = ~pal74(nc$births1974),
fillOpacity = 0.7,
opacity = 1,
color = "white",
weight = 2)
```
* Let's add some `highlightOptions`
```{r first-leaflet-map1j, eval=TRUE}
m1 %>%
addPolygons(
fillColor = ~pal74(nc$births1974),
fillOpacity = 0.7,
color = "white",
opacity = 1,
weight = 2,
highlight = highlightOptions( #<<
weight = 3, #<<
color = "blue", #<<
fillOpacity = 1, #<<
bringToFront = TRUE)) #<<
```
## Let's add some labels!
`sprintf`: returns a character vector containing a formatted combination of text and variable values.
```{r Make our labels}
labels <- sprintf("<strong>%s</strong><br/>%g births",
nc$county, nc$births1974) %>% lapply(htmltools::HTML)
head(labels, 1)
```
html - markup language for the web
* `<strong>` = bold; `<br/>` = new line
PHP - Hypertext Preprocessor
* `%s` = place holder for a character string; `%g` = general format place holder for a number
```{r first-leaflet-map1k, eval=TRUE}
(m1 <- m1 %>%
addPolygons(data = nc,
fillColor = ~pal74(nc$births1974),
fillOpacity = 0.7,
color = "white",
opacity = 1,
weight = 2,
highlight = highlightOptions(
weight = 3,
color = "blue",
fillOpacity = 1,
bringToFront = TRUE),
label = labels)) #<<
```
* Let's add a legend
```{r first-leaflet-map1l, eval=TRUE}
m1 <- m1 %>%
addLegend( #<<
position = "bottomright", #<<
pal = pal74, #<<
values = ~nc$births1974, #<<
title = "Births by county in 1974", #<<
opacity = 1) #<<
m1
```
## Let's create a second map
* Let's create a second map of births in 1979.
* First we'll need to create a new set of labels
```{r labels for second map}
labels79 <- sprintf(
"<strong>%s</strong><br/>%g births",
nc$county, nc$births1979
) %>% lapply(htmltools::HTML)
```
## Let's create a second map
```{r second map}
m2 <- leaflet(data = nc) %>%
addProviderTiles(providers$Stamen.Terrain) %>%
setView(lng = -80, lat = 34.5, zoom = 6) %>%
addPolygons(
fillColor = ~pal79(nc$births1979),
fillOpacity = 0.7,
color = "white",
opacity = 1,
weight = 2,
highlight = highlightOptions(
weight = 3,
color = "blue",
fillOpacity = 1,
bringToFront = TRUE),
label = labels79)
```
```{r leaflet-map2a, eval=TRUE}
(m2 <- m2 %>%
addLegend(
position = "bottomright",
pal = pal79,
values = ~nc$births1979,
title = "Births by country in 1979",
opacity = 1))
```
## Placing two maps side by side
```{r leaflet-map3}
leafsync::sync(m1, m2, ncol = 2, sync = "all")
```
# Leaflet maps with points
```{r leaflet-map-points, echo = TRUE}
work <- data.frame(
"location" = c("Valparaíso, Chile",
"Curitiba, Brasil",
"Sable Island, Nova Scotia",
"Greifswald, Germany",
"Arusha, Tanzania",
"Kigali, Rwanda",
"Kingston, Jamaica",
"Asunción, Paraguay",
"East Kilbride, Scotland"),
"institute" = c("Instituto de Fomento Pesquero",
"Universidade Federal do Paraná",
"Dalhousie University",
"Friedrich Loeffler Institut",
"Nelson Mandela African Institute of Science and Technology",
"National Institute of Statistics Rwanda",
"Caribbean National Statistical Offices",
"El Ministerio de Salud Pública y Bienestar Social y el Ministerio de Educación y Ciencias - Paraguay",
"Foreign Commonwealth Development Office"),
"work" = c("Chilean Pink Cusk Eel",
"Fox rabies",
"Grey seals",
"Fox rabies",
"Teaching",
"Teaching",
"Teaching",
"Teaching",
"Teaching"),
"lat" = c(-33.0472,
-25.4290,
43.9337,
54.0865,
-3.3995,
-1.9415,
18.0179,
-25.2637,
55.760869),
"lon" = c(-71.6127,
-49.2671,
-59.9149,
13.3923,
36.7968,
30.0574,
-76.8099,
-57.5759,
-4.22407),
"icon" = c("fish",
"disease",
"gps",
"disease",
"training",
"training",
"training",
"training",
"training"))
```
```{r data-preview}
work %>%
kbl() %>%
kable_paper("hover")
```
```{r work-leaflet, eval=TRUE}
leaflet(work) %>%
addProviderTiles(providers$Stamen.Watercolor) %>%
addProviderTiles(providers$Stamen.TerrainLabels) %>%
addCircleMarkers(~lon, ~lat)
```
* **Your Turn*** What else can you change about addCircleMarkers? Hint: Type `??addControl` Try adding: `clusterOptions = markerClusterOptions()` to your map.
* Add labels
```{r point-labels}
labels <- sprintf(
"<strong>%s</strong>",
work$institute) %>% lapply(htmltools::HTML)
```
```{r}
(work_map <- leaflet(work) %>%
addProviderTiles(providers$Stamen.Watercolor) %>%
addProviderTiles(providers$Stamen.TerrainLabels) %>%
addCircleMarkers(~lon, ~lat, popup = ~labels))
```