-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsf_presentation.html
576 lines (452 loc) · 16.4 KB
/
sf_presentation.html
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
<!DOCTYPE html>
<html lang="" xml:lang="">
<head>
<title>Coordinate Reference Systems with sf</title>
<meta charset="utf-8" />
<meta name="author" content="Lisa Pramann & Caitlin Sarro" />
<script src="sf_presentation_files/header-attrs/header-attrs.js"></script>
<link href="sf_presentation_files/remark-css/default.css" rel="stylesheet" />
<link href="sf_presentation_files/remark-css/metropolis.css" rel="stylesheet" />
<link href="sf_presentation_files/remark-css/metropolis-fonts.css" rel="stylesheet" />
</head>
<body>
<textarea id="source">
class: center, middle, inverse, title-slide
# Coordinate Reference Systems with sf
## Workshop: I2DS Tools for Data Science
### Lisa Pramann & Caitlin Sarro
### Hertie School
### November 4th 2021
---
<style type="text/css">
@media print { # print out incremental slides; see https://stackoverflow.com/questions/56373198/get-xaringan-incremental-animations-to-print-to-pdf/56374619#56374619
.has-continuation {
display: block !important;
}
}
</style>
#Agenda
##1. Modelling the world
##2. What are CRS?
##3. CRS and Datums
##4. CRS in R
###4.1 Two Key Features
###4.2 Spatial Data Operations
##5. Further Resources
---
#Modelling the World
##How does the Earth really look like?
Refreshing you knowledge from your Geo-course during high school/undergrad-studies...
.pull-left-small2[
<div align="center">
<br>
<img src="http://www.geo.hunter.cuny.edu/~jochen/gtech201/lectures/lec6concepts/Datums/Basics%20of%20datums_files/image001.gif" width=700>
</div>
]
---
#What is a “Coordinate Reference System” (CRS) ?
##(= Geographic Coordination System or Spatial Reference System)
.pull-left[
- Used to model the World
- Set locations
- Utilize
- latitude (horizontal)
- longitude (vertical)
- basis for planar coordinates and GIS (Geoinformation Systems)
<div align="center">
<img src="sf_presentation_files/figure-html/planar_coordinates.jpg" width=400>
</div> <div align="center">
[Sreedevi, 2021 ](https://www.analyticsvidhya.com/blog/2021/09/how-to-visualise-data-in-maps-using-geopandas/)
]</div>
.pull-right[
<div align="center">
<br><br>
<img src="sf_presentation_files/figure-html/long_lat.jpg" width=400>
</div> <div align="center">
[Mike Mitter, 2019](https://www.mikemitterer.at/2019/07/11/latitude-longitude-module-ist-auf-npmjs/
)
] </div>
---
#CRS and Datums
**As you have seen the Ellipsoid cannot model the earth (not even the Geoid) completely**
Therefore, different Coordinate Reference Systems exist:
.pull-left[
- **World Geodetic System**
- (WGS84, EPSG:4326)
- approximates the whole earth
- standard model
- **North American Datum**
- (NAD83, EPSG:6269)
- **Australian Geodetic Datum**
- (AGD84, EPSG:420)
- Datums can usually be converted to one another.
]
.pull-right[
<div align="center">
<br>
<img src="https://www.icsm.gov.au/sites/default/files/inline-images/regional_0.jpg" width=450>
</div> <div align="center">
[IOSM Austrailia, 2021 ](https://www.icsm.gov.au/sites/default/files/inline-images/regional_0.jpg)
]</div>
---
# Introduction to sf package
.pull-right[
<div align="center">
<br>
<img src="sf_presentation_files/figure-html/geomet.jpg" width=400>
</div> <div align="right">
[Geocomputation with R, 2021 ](https://edzer.github.io/rstudio_conf/#13)]</div>
<b> Simple Features (sf) </b> describe how objects in the real world (such as a building or a tree) can be represented in computers.
Features have a <i>geometry </i> describing <i>where </i> on Earth the feature is located, and they have attributes, which describe other properties.
These geometries are represented by points, lines or polygons, or collections thereof (no curves).
## Example
Let’s look at how data is catagorized in a simple feature:
```r
R> class(nc) #nc is a shapefile for North Carolina
```
```
## [1] "sf" "data.frame"
```
```r
R> attr(nc, "sf_column")
```
```
## [1] "geometry"
```
---
# CRS in sf
Let’s look at how CRSs are stored in R spatial objects and how they can be set. For this, we need to read-in a vector dataset:
```r
R> vector_filepath <- system.file("shapes/world.gpkg", package = "spData")
R> new_vector <- read_sf(vector_filepath)
```
Our new object, `new_vector`, is a polygon representing a world map data from Natural Earth with a few variables from World Bank (?spData::world).
```r
R> head(new_vector, 3)
```
```
## Simple feature collection with 3 features and 10 fields
## Geometry type: MULTIPOLYGON
## Dimension: XY
## Bounding box: xmin: -180 ymin: -18.28799 xmax: 180 ymax: 27.65643
## Geodetic CRS: WGS 84
## # A tibble: 3 x 11
## iso_a2 name_long continent region_un subregion type area_km2 pop lifeExp
## <chr> <chr> <chr> <chr> <chr> <chr> <dbl> <dbl> <dbl>
## 1 FJ Fiji Oceania Oceania Melanesia Sove~ 19290. 8.86e5 70.0
## 2 TZ Tanzania Africa Africa Eastern ~ Sove~ 932746. 5.22e7 64.2
## 3 EH Western S~ Africa Africa Northern~ Inde~ 96271. NA NA
## # ... with 2 more variables: gdpPercap <dbl>, geom <MULTIPOLYGON [°]>
```
---
#Key Features (1)
## 1 | Retrieve coordinate reference system from object
.pull-left[
In sf the CRS of an object can be retrieved using `st_crs()`.
```r
R> st_crs(new_vector) # get CRS
```
]
.pull-right[
```r
Coordinate Reference System:
User input: WGS 84
wkt:
GEOGCRS["WGS 84",
DATUM["World Geodetic System 1984",
ELLIPSOID["WGS 84",6378137,298.257223563,
LENGTHUNIT["metre",1]]],
PRIMEM["Greenwich",0,
ANGLEUNIT["degree",0.0174532925199433]],
CS[ellipsoidal,2],
AXIS["geodetic latitude (Lat)",north,
ORDER[1],
ANGLEUNIT["degree",0.0174532925199433]],
AXIS["geodetic longitude (Lon)",east,
ORDER[2],
ANGLEUNIT["degree",0.0174532925199433]],
USAGE[
SCOPE["Horizontal component of 3D system."],
AREA["World."],
BBOX[-90,-180,90,180]],
ID["EPSG",4326]]
```
]
---
#Key Features (2)
## 1 | Retrieve coordinate reference system from object
The `st_crs` function also has one helpful feature – we can retrieve some additional information about the used CRS.
For example, try to run:
```r
R> st_crs(new_vector)$IsGeographic #to check if the CRS is geographic or not
```
```
## [1] TRUE
```
```r
R> st_crs(new_vector)$units_gdal #to find out the CRS units
```
```
## [1] "degree"
```
```r
R> st_crs(new_vector)$srid #extracts its SRID (projection code common with GIS)
```
```
## [1] "EPSG:4326"
```
```r
R> st_crs(new_vector)$proj4string #extracts the proj4string representation
```
```
## [1] "+proj=longlat +datum=WGS84 +no_defs"
```
---
#Key Features (3)
## 2 | Add or Change CRS
When the CRS is missing or the wrong CRS is set, the `st_set_crs()` function can be used. An important note is that replacing CRS does not re-project data and maintains data integrity.
```r
R> # For transformations use 'st_set_crs'
R> CRS_vector <- sf::st_set_crs(world, "EPSG:4326") # set CRS
```
```r
R> # Shifting the projection to center on Brussels using the CRS
R> world_view_brussels <- st_transform(world, crs = "+proj=laea +x_0=0 +y_0=0 +lon_0=50.8503396 +lat_0=4.3517103")
```
.pull-left[
<div align="left">
<img src="sf_presentation_files/figure-html/world_plot.png" width=350>
]</div>
.pull-right[
<div align="center">
<img src="sf_presentation_files/figure-html/brussels_plot.png" width=350>
]</div>
---
# How to work with Spatial Data (1)
##Some simple spatial data operations
1) **Geometric measurements**
- CRSs include information about spatial units, however it is generally difficult to work with units to do geometric calculations (see difference of latitude and longitude data and planar coordinate systems) -> the recent version of sf utilizes the units package which output is by default provided in m^2.
.pull-left[
Lets see how that looks like for Belgium. We use the world data from the `spData` package:
```r
R> Belgium <- world %>%
+ filter(name_long == "Belgium")
R> st_area(Belgium)
```
```
## 30019548314 [m^2]
```
]
.pull-right[
The number appears really big, better to set the units to km^2:
```r
R> units::set_units(st_area(Belgium), km^2)
```
```
## 30019.55 [km^2]
```
]
---
# How to work with Spatial Data (2)
##Some simple spatial data operations
2) **Geometric measurements**
- sf can also measure distances between two points based on geometric data.
- The package `spData` contains geometric data on London's districts `lnd` and a dataset of cycle hire points in London `cycle_hire`.
- We want to measure the distance from the cycle hire point at the Palace Gate to the centre of Redbridge.
- The default of `st_distance()` is in m. We could use /1000 to get km.
```r
R> cycle_station_palace <- cycle_hire %>%
+ filter(name == "Palace Gate")
R> redbridge <- lnd %>%
+ filter(NAME == "Redbridge")
R> redbridge_centroid <- st_centroid(redbridge) #gives central point in selected district
R> st_distance(cycle_station_palace, redbridge_centroid)
```
```
## Units: [m]
## [,1]
## [1,] 20258.6
```
---
# How to work with Spatial Data (3)
##Creating maps with geometric data and sf
There a different ways to create maps based on geometric data.
.pull-left[
1) One simple way is by using `ggplot()` in combination with `geom_sf()` from the `sf` package
Lets have a look at data from the US retrieved from the `spData` package:
```r
R> ggplot() +
+ geom_sf(data = us_states) +
+ #For simple plots, you will only need geom_sf()
+ coord_sf(crs = st_crs(4326))
R> #ensures that all layers use a common CRS
R> #(would not be needed in this case)
```
]
.pull-right[
<div align="center">
<img src="sf_presentation_files/figure-html/usstates.jpg" width=600>
</div>]
---
# How to work with Spatial Data (4)
##Creating maps with geometric data and sf
There a different ways to create maps based on geometric data.
.pull-left[
2) `sf` also comes with a `plot()` function which creates a map of a sf object with one or more attributes.
Lets have a look at data from the US retrieved from the `spData` package:
```r
R> us_income <- left_join(
+ #joining two data frames from spData to
+ #attribute Median Income in 2015 to us_states
+ us_states, us_states_df,
+ by = c("NAME" = "state"))
```
```r
R> us_income_plot <- plot(us_income["median_income_15"],
+ main = "Median income per State in 2015")
```
]
.pull-right[
<div align="center">
<img src="sf_presentation_files/figure-html/us_2015.jpg" width=450>
</div>]
]
---
#Conclusion
Things to take-away or have a closer look at
###- `sf` offers a comprehensive way to access and model with CRS data
###- Remember the most common CRS in the world (WGS84/ EPSG code: 4326) and experiment with different codes.
###- *Public Policy* application: CRS is used in combination with other tools for visualization purposes by mapping certain data e.g. median income, voting behavior, COVID-vaccination rates, etc.
###- Feel free to build on the skills in this session and have a look at how to use this for data visualization purposes
---
#Further Links and Resources
Not yet enough of CRS and `sf`? Check out our resources and additional references:
### Most `Credit` to Robin Lovelance [Geocomputation with R, 2021](https://edzer.github.io/rstudio_conf/#13)
### [Presentation Tidy Spatial Data Analysis 2018](https://edzer.github.io/rstudio_conf/#1)
###[Blog WZB 2019 - Zooming in on maps with sf and ggplot2](https://datascience.blog.wzb.eu/2019/04/30/zooming-in-on-maps-with-sf-and-ggplot2/)
### [Mapping in R with Emiliy Burchfield](https://www.emilyburchfield.org/courses/eds/making_maps_in_r)
---
# <center>Thank you!
## Now onto the in-class session...
</textarea>
<style data-target="print-only">@media screen {.remark-slide-container{display:block;}.remark-slide-scaler{box-shadow:none;}}</style>
<script src="https://remarkjs.com/downloads/remark-latest.min.js"></script>
<script>var slideshow = remark.create({
"highlightStyle": "github",
"highlightLines": true,
"countIncrementalSlides": false,
"ratio": "16:9",
"hash": true
});
if (window.HTMLWidgets) slideshow.on('afterShowSlide', function (slide) {
window.dispatchEvent(new Event('resize'));
});
(function(d) {
var s = d.createElement("style"), r = d.querySelector(".remark-slide-scaler");
if (!r) return;
s.type = "text/css"; s.innerHTML = "@page {size: " + r.style.width + " " + r.style.height +"; }";
d.head.appendChild(s);
})(document);
(function(d) {
var el = d.getElementsByClassName("remark-slides-area");
if (!el) return;
var slide, slides = slideshow.getSlides(), els = el[0].children;
for (var i = 1; i < slides.length; i++) {
slide = slides[i];
if (slide.properties.continued === "true" || slide.properties.count === "false") {
els[i - 1].className += ' has-continuation';
}
}
var s = d.createElement("style");
s.type = "text/css"; s.innerHTML = "@media print { .has-continuation { display: none; } }";
d.head.appendChild(s);
})(document);
// delete the temporary CSS (for displaying all slides initially) when the user
// starts to view slides
(function() {
var deleted = false;
slideshow.on('beforeShowSlide', function(slide) {
if (deleted) return;
var sheets = document.styleSheets, node;
for (var i = 0; i < sheets.length; i++) {
node = sheets[i].ownerNode;
if (node.dataset["target"] !== "print-only") continue;
node.parentNode.removeChild(node);
}
deleted = true;
});
})();
(function() {
"use strict"
// Replace <script> tags in slides area to make them executable
var scripts = document.querySelectorAll(
'.remark-slides-area .remark-slide-container script'
);
if (!scripts.length) return;
for (var i = 0; i < scripts.length; i++) {
var s = document.createElement('script');
var code = document.createTextNode(scripts[i].textContent);
s.appendChild(code);
var scriptAttrs = scripts[i].attributes;
for (var j = 0; j < scriptAttrs.length; j++) {
s.setAttribute(scriptAttrs[j].name, scriptAttrs[j].value);
}
scripts[i].parentElement.replaceChild(s, scripts[i]);
}
})();
(function() {
var links = document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
if (/^(https?:)?\/\//.test(links[i].getAttribute('href'))) {
links[i].target = '_blank';
}
}
})();
// adds .remark-code-has-line-highlighted class to <pre> parent elements
// of code chunks containing highlighted lines with class .remark-code-line-highlighted
(function(d) {
const hlines = d.querySelectorAll('.remark-code-line-highlighted');
const preParents = [];
const findPreParent = function(line, p = 0) {
if (p > 1) return null; // traverse up no further than grandparent
const el = line.parentElement;
return el.tagName === "PRE" ? el : findPreParent(el, ++p);
};
for (let line of hlines) {
let pre = findPreParent(line);
if (pre && !preParents.includes(pre)) preParents.push(pre);
}
preParents.forEach(p => p.classList.add("remark-code-has-line-highlighted"));
})(document);</script>
<script>
slideshow._releaseMath = function(el) {
var i, text, code, codes = el.getElementsByTagName('code');
for (i = 0; i < codes.length;) {
code = codes[i];
if (code.parentNode.tagName !== 'PRE' && code.childElementCount === 0) {
text = code.textContent;
if (/^\\\((.|\s)+\\\)$/.test(text) || /^\\\[(.|\s)+\\\]$/.test(text) ||
/^\$\$(.|\s)+\$\$$/.test(text) ||
/^\\begin\{([^}]+)\}(.|\s)+\\end\{[^}]+\}$/.test(text)) {
code.outerHTML = code.innerHTML; // remove <code></code>
continue;
}
}
i++;
}
};
slideshow._releaseMath(document);
</script>
<!-- dynamically load mathjax for compatibility with self-contained -->
<script>
(function () {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-MML-AM_CHTML';
if (location.protocol !== 'file:' && /^https?:/.test(script.src))
script.src = script.src.replace(/^https?:/, '');
document.getElementsByTagName('head')[0].appendChild(script);
})();
</script>
</body>
</html>