-
Notifications
You must be signed in to change notification settings - Fork 7
/
gis-r.html
672 lines (460 loc) · 17.9 KB
/
gis-r.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
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
<!DOCTYPE html>
<html>
<head>
<title>Introduction to GIS in R</title>
<meta charset="utf-8">
<meta name="author" content="Angela Li @CivicAngela Center for Spatial Data Science, UChicago Slides available at http://bit.ly/harris-gis" />
<meta name="date" content="2018-05-18" />
<link href="libs/remark-css/default.css" rel="stylesheet" />
<link href="libs/remark-css/default-fonts.css" rel="stylesheet" />
</head>
<body>
<textarea id="source">
class: center, middle, inverse, title-slide
# Introduction to GIS in R
## 🌎 🗺<br/>with sf and tmap
### Angela Li <br> <span class="citation">@CivicAngela</span> <br> Center for Spatial Data Science, UChicago <br> Slides available at <a href="http://bit.ly/harris-gis" class="uri">http://bit.ly/harris-gis</a>
### 2018-05-18
---
class: center, middle, inverse
# Want to try out the code in this presentation?
## Data and code are located at my Github repo [here](https://github.com/angela-li/gis-r).
---
# Three parts to this talk:
## 1. Why spatial data in R?
## 2. A quick tutorial
## 3. Examples and resources
---
class: inverse, center, middle
# Why spatial data in R?
---
class: inverse
# I had to make a map for a class
![](images/gis-map.png)
---
# Here's how you do it with a traditional GIS
![](images/gis-process.png)
---
# This is fine, until
--
👎 You want to remake your map with a slightly different set of data and have to redo everything
--
👎 You want to make a bunch of maps quickly
--
👎 You forgot what buttons you even clicked to make the map
--
👎👎👎 **The GIS software crashes!**
![](images/this-is-fine.png)
---
class: inverse, center, middle
# Enter R
## (and geographic data science)
---
# A map from my thesis
![](images/thesis-map.png)
---
# And the code used to produce it
```r
library(tidyverse)
library(sf)
library(tmap)
sales <- read_csv("output/sales-tidy.csv")
tracts <- st_read("data/orig/shapefiles/detroit_tracts.shp")
tracts <- rename(tracts, tract = GEOID)
sales <- sales %>%
right_join(tracts, ., by = "tract")
med_sales_map <- tm_shape(sales, unit = "mi") +
tm_fill("med_price", palette = "Blues", breaks = quantile(a$med_price), title = "Median Sales Price") +
tm_facets("after_hhf") +
tm_shape(tracts) +
tm_borders() +
tm_compass(fontsize = 0.6, color.dark = "dark grey") +
tm_scale_bar(color.dark = "dark grey")
save_tmap(med_sales_map, "doc/figs/med_sales_map.png")
```
---
class: center, middle
# Not much code = pretty good results
Thanks, `sf` and `tmap`!
![](images/sf-hex.gif)
---
class: inverse, center, middle
# A quick tutorial
---
# Getting started
Install the `sf` and `tmap` packages.
```r
install.packages("sf")
install.packages("tmap")
```
- `sf` stores spatial data as (tidyverse-friendly!) dataframes
- `sp` is the original way to store spatial data in R, but it doesn't use dataframes
- Many spatial statistics and mapping packages still rely on `sp`, so you'll probably encounter a `SpatialPolygonsDataFrame` at some point.
- No worries, you can convert from `sf` to `sp` and vice versa pretty easily
- `tmap` provides a quick way to make useful thematic maps and works directly with spatial objects
- There are a bunch of other packages you can use to make interactive maps (`mapview`, `leaflet`, `ggplot2`, `shiny`), which I won't go into today
---
# Get some data
- You're looking for "shapefiles" but data with XY coordinates works too
- Many packages have been developed to acquire spatial data:
- `spData`
- `tidycensus`
- `usaboundaries`
- `osmdata`
- etc.
- If you have address data, you can geocode (translate addresses to latitude and longitude) with the `opencage` package, which I won't discuss today
- Check out all of these spatial packages later!
---
# Let's download some data
## Support your [local open data portal](https://data.cityofchicago.org/)
![](images/chi-data-1.png)
---
![](images/chi-data-2.png)
---
![](images/chi-data-3.png)
---
![](images/chi-data-4.png)
---
# You've downloaded the data
### What the heck are all of these files??
![](images/shapefile-files.png)
In general:
- .shp is the actual shape ("feature geometry") of the data
- .dbf represents the attributes associated with each shape
- .prj tells you how 3-D coordinates are "projected" into a 2-D map
- .sbn, .sbx, .shx are indexes that make it easier to work quickly with spatial data
FYI: spatial data tends to be BIG (because you have to store all the info about how to make the shapes!)
---
# Load the R package, and the data
```r
# Load package
library(sf)
```
```
## Linking to GEOS 3.6.1, GDAL 2.1.3, proj.4 4.9.3
```
```r
# Read in shapefile
chi <- st_read("data/Neighborhoods_2012b.shp")
```
```
## Reading layer `Neighborhoods_2012b' from data source `/Users/angela/Desktop/R-Projects/Teaching/gis-r/data/Neighborhoods_2012b.shp' using driver `ESRI Shapefile'
## Simple feature collection with 98 features and 4 fields
## geometry type: MULTIPOLYGON
## dimension: XY
## bbox: xmin: 1091131 ymin: 1813892 xmax: 1205199 ymax: 1951669
## epsg (SRID): NA
## proj4string: +proj=tmerc +lat_0=36.66666666666666 +lon_0=-88.33333333333333 +k=0.9999749999999999 +x_0=300000 +y_0=0 +datum=NAD83 +units=us-ft +no_defs
```
---
# Take a look at the data
```r
head(chi)
```
```
## Simple feature collection with 6 features and 4 fields
## geometry type: MULTIPOLYGON
## dimension: XY
## bbox: xmin: 1145372 ymin: 1871188 xmax: 1182449 ymax: 1918816
## epsg (SRID): NA
## proj4string: +proj=tmerc +lat_0=36.66666666666666 +lon_0=-88.33333333333333 +k=0.9999749999999999 +x_0=300000 +y_0=0 +datum=NAD83 +units=us-ft +no_defs
## PRI_NEIGH SEC_NEIGH SHAPE_AREA SHAPE_LEN
## 1 Grand Boulevard BRONZEVILLE 48492503 28196.837
## 2 Printers Row PRINTERS ROW 2162138 6864.247
## 3 United Center UNITED CENTER 32520513 23101.364
## 4 Sheffield & DePaul SHEFFIELD & DEPAUL 10482592 13227.050
## 5 Humboldt Park HUMBOLDT PARK 125010426 46126.751
## 6 Garfield Park GARFIELD PARK 89976070 44460.919
## geometry
## 1 MULTIPOLYGON (((1182322 187...
## 2 MULTIPOLYGON (((1176453 189...
## 3 MULTIPOLYGON (((1165664 190...
## 4 MULTIPOLYGON (((1167948 191...
## 5 MULTIPOLYGON (((1145647 190...
## 6 MULTIPOLYGON (((1157952 190...
```
--
# `sf` objects are `data.frame`s!
```r
class(chi)
```
```
## [1] "sf" "data.frame"
```
---
# Make your first map (1)
```r
# Map it using base R: just shape outlines
plot(st_geometry(chi))
```
![](gis-r_files/figure-html/unnamed-chunk-6-1.png)<!-- -->
---
# Make your first map (2)
```r
# This maps all the attributes
plot(chi)
```
![](gis-r_files/figure-html/unnamed-chunk-7-1.png)<!-- -->
---
class: inverse, middle
# Get more interesting data
Lots of great cleaned datasets at my research center's website to play with.
<center> https://geodacenter.github.io/data-and-lab/ </center>
![](images/geoda-data.png)
---
![](images/geoda-data-1.png)
---
![](images/geoda-data-2.png)
---
# Make a second map (1)
```r
chi2 <- st_read("data/ComArea_ACS14_f.shp")
```
```
## Reading layer `ComArea_ACS14_f' from data source `/Users/angela/Desktop/R-Projects/Teaching/gis-r/data/ComArea_ACS14_f.shp' using driver `ESRI Shapefile'
## Simple feature collection with 77 features and 86 fields
## geometry type: MULTIPOLYGON
## dimension: XY
## bbox: xmin: -87.94011 ymin: 41.64454 xmax: -87.52414 ymax: 42.02304
## epsg (SRID): 4326
## proj4string: +proj=longlat +ellps=WGS84 +no_defs
```
For reference:
- `geometry type` describes the basic structure of the spatial data. You could have points, polygons, lines, and more.
- `bbox` gives the bounding box for the data, and can be used to crop other layers when you make a map.
- `epsg (SRID)` is a special code that indicates what projection is being used. When in doubt, `4326` is a good one.
- `proj4string` refers to the same thing as the EPSG code. If the string starts with `+proj=longlat`, that means your data is **unprojected**.
---
# Make a second map (2)
Let's make a choropleth map of population density by neighborhood!
```r
# Check what variables we have
names(chi2)
```
```
## [1] "ComAreaID" "community" "TRACTCnt" "shape_area" "shape_len"
## [6] "Pop2012" "Pop2014" "PopChng" "PopM" "PopMP"
## [11] "PopF" "PopFP" "Under5" "Under5P" "Under18"
## [16] "Under18P" "Over18" "Over18P" "Over21" "Over21P"
## [21] "Over65" "Over65P" "Wht14" "Wht14P" "Blk14"
## [26] "Blk14P" "AI14" "AI14P" "AS14" "AS14P"
## [31] "NHP14" "NHP14P" "Oth14" "Oth14P" "Hisp14"
## [36] "Hisp14P" "Property_C" "PropCrRt" "Violent_C" "VlntCrRt"
## [41] "PerCInc14" "PPop14" "Pov14" "field_37" "ChldPov14"
## [46] "NoHS14" "HSGrad14" "SmClg14" "ClgGrad14" "LaborFrc"
## [51] "Unemp14" "Pov50" "Pov50P" "Pov125" "Pov125P"
## [56] "Pov150" "Pov150P" "Pov185" "Pov185P" "Pov200"
## [61] "Pov200P" "COIave" "HISave" "SESave" "Hlitave"
## [66] "BirthRate" "FertRate" "LoBirthR" "PrenScrn" "PretBrth"
## [71] "TeenBirth" "Assault" "BrstCancr" "CancerAll" "Colorect"
## [76] "DiabetM" "FirearmM" "InfntMR" "LungCancer" "ProstateC"
## [81] "Stroke" "ChlBLLS" "ChlLeadP" "GonorrF" "GonorrM"
## [86] "Tuberc" "geometry"
```
---
# Make a second map (3)
Since we have population and area, we're going to calculate population density using the `dplyr` package.
```r
# Calculate population density
library(dplyr)
```
```
##
## Attaching package: 'dplyr'
```
```
## The following objects are masked from 'package:stats':
##
## filter, lag
```
```
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
```
```r
chi2 <- mutate(chi2, Pop2014 = Pop2014/shape_area)
```
```
## Warning: package 'bindrcpp' was built under R version 3.4.4
```
---
```r
# Map population density by neighborhood
plot(chi2["Pop2014"])
```
![](gis-r_files/figure-html/unnamed-chunk-11-1.png)<!-- -->
---
# Use `tmap` to make a prettier map
```r
library(tmap)
tm_shape(chi2) +
tm_fill("Pop2014", palette = "Purples",
title = "Population by Neighborhood, 2014")
```
---
```
## Warning: package 'tmap' was built under R version 3.4.4
```
![](gis-r_files/figure-html/unnamed-chunk-13-1.png)<!-- -->
---
class: inverse, center, middle
# Let's do some spatial analysis!
---
# How are grocery stores and population related?
Time to add a point layer with locations of grocery stores.
```r
groceries <- st_read("data/groceries.shp")
```
```
## Reading layer `groceries' from data source `/Users/angela/Desktop/R-Projects/Teaching/gis-r/data/groceries.shp' using driver `ESRI Shapefile'
## Simple feature collection with 149 features and 14 fields
## geometry type: POINT
## dimension: XY
## bbox: xmin: 1124188 ymin: 1826196 xmax: 1201803 ymax: 1950151
## epsg (SRID): NA
## proj4string: +proj=tmerc +lat_0=36.66666666666666 +lon_0=-88.33333333333333 +k=0.9999749999999999 +x_0=300000.0000000001 +y_0=0 +ellps=GRS80 +units=us-ft +no_defs
```
Note that this is a `POINT` object, and that it has a projection: `+proj=tmerc` (Transverse Mercator). If we want to plot this in the same map as the neighborhood boundaries, we will need to make sure both files have the **same projection**.
⭐ This is a key source of frustration when working with spatial data. If some layers aren't showing up when you make a map, check that they all have the same projection! ⭐
---
# Project the neighborhood data
You generally project the data that has the `+proj=longlat` string, because it is initially **unprojected**.
```r
# Get the CRS (coordinate reference system) of the groceries point data
groceries_crs <- st_crs(groceries)
# Project the neighborhood boundaries
chi2 <- st_transform(chi2, groceries_crs)
```
---
# Plot population and grocery stores
```r
# Plot both
tm_shape(chi2) +
tm_borders() +
tm_fill("Pop2014", palette = "Purples",
title = "Grocery Stores and Population Density, 2014") +
tm_shape(groceries) +
tm_dots(title = "Groceries", size = 0.1, col = "black")
```
---
![](gis-r_files/figure-html/unnamed-chunk-17-1.png)<!-- -->
---
class: inverse, center, middle
# You can also use dplyr to perform analysis!
---
# Which neighborhoods in Chicago have the most grocery stores?
```r
library(dplyr)
chi2 %>%
st_join(groceries, .) %>%
group_by(community) %>%
tally() %>%
arrange(desc(n))
```
```
## Simple feature collection with 55 features and 2 fields
## geometry type: GEOMETRY
## dimension: XY
## bbox: xmin: 1124188 ymin: 1826196 xmax: 1201803 ymax: 1950151
## epsg (SRID): NA
## proj4string: +proj=tmerc +lat_0=36.66666666666666 +lon_0=-88.33333333333333 +k=0.9999749999999999 +x_0=300000.0000000001 +y_0=0 +ellps=GRS80 +units=us-ft +no_defs
## # A tibble: 55 x 3
## community n geometry
## <fct> <int> <MULTIPOINT [US_survey_foot]>
## 1 NEAR NORTH SIDE 12 (1169391 1910436, 1171916 1908252, 1174283 19056…
## 2 LOGAN SQUARE 8 (1150226 1915696, 1151916 1915701, 1153076 19184…
## 3 LAKE VIEW 7 (1165054 1922112, 1165147 1919657, 1166327 19242…
## 4 LOWER WEST SIDE 7 (1160692 1889319, 1162087 1889703, 1162758 18876…
## 5 NEAR WEST SIDE 7 (1165889 1894599, 1168996 1898801, 1171065 18998…
## 6 BELMONT CRAGIN 6 (1132379 1917230, 1133303 1916051, 1134857 19206…
## 7 PORTAGE PARK 5 (1138161 1931033, 1139403 1928722, 1143627 19270…
## 8 SOUTH LAWNDALE 5 (1150164 1886133, 1150463 1886334, 1154568 18865…
## 9 MCKINLEY PARK 4 (1161716 1880466, 1163330 1881780, 1163933 18828…
## 10 MORGAN PARK 4 (1162303 1832900, 1162826 1830936, 1167502 18268…
## # ... with 45 more rows
```
---
# More advanced spatial analysis involves buffers, distance, intersections, etc.
Code from my thesis:
```r
get_point_counts_in_buffer <- function(points_to_buffer,
points_to_intersect,
buffer_size = 500) {
number_points_within_buffer <- points_to_buffer %>%
st_buffer(buffer_size) %>%
st_contains(points_to_intersect) %>%
map_dbl(length) %>%
tibble(pts_in_buffer = .)
return(number_points_within_buffer)
}
```
---
# And what it did:
![](images/method-counts.png)
---
class: inverse, middle, center
# Now a few resources for learning more...
---
# A few other key packages to check out
- `tidycensus`: all census and ACS data from past several years, delivered directly into R
- `tigris`: TIGERline shapefiles (boundaries, etc)
- `osmdata`: OpenStreetMap data, delivered directly into R
- `spData`: sample spatial datasets to play around with in all sorts of formats
- `raster`: many functions for working with raster data
- `opencage`: geocoding
- `shiny`: the workhorse for R interactive webapps
---
# Resources to get you started
- [Geocomputation with R](https://geocompr.robinlovelace.net/), an open-source spatial analysis textbook currently under development, and the best resource for this new `sf` stuff, by Robin Lovelace, Jakub Nowosad, and Jannes Muenchow
--
- A great [Datacamp intro course](https://www.datacamp.com/courses/spatial-analysis-in-r-with-sf-and-raster) on sf by Zev Ross (the first part is free)
--
- [sf documentation](https://r-spatial.github.io/sf/) by Edzer Pebesma
--
- Jakub Nowosad's [slides on GIS with R](https://cdn.rawgit.com/Nowosad/gis_with_r_how_to_start/aea08f46/gis_with_r_start.html), off of which these slides are informed
--
- I tweet about GIS in R sometimes (read: a lot): [@CivicAngela](https://twitter.com/CivicAngela)
---
class: center, middle
# Thanks!
**Want to try out the code in this presentation? Data and code are located at my Github repo [here](https://github.com/angela-li/gis-r).**
Slides created via the R package [xaringan](https://github.com/yihui/xaringan) by [Yihui Xie](https://twitter.com/xieyihui?lang=en). If you're interested in learning how to make slide decks in R, check out Alison's [awesome guide here](https://github.com/rladies/resources/blob/master/xaringan-slides/how_to_use.md). It's focused on using the R-Ladies theme, but you can generalize!
Slides available at <font style="text-transform: lowercase;"><http://bit.ly/harris-gis></font> <br>
Contact me at @[CivicAngela](https://twitter.com/CivicAngela), ali6@uchicago.edu with feedback and any additional comments!
</textarea>
<script src="https://remarkjs.com/downloads/remark-latest.min.js"></script>
<script>var slideshow = remark.create({
"highlightStyle": "github",
"highlightLines": true,
"countIncrementalSlides": false
});
if (window.HTMLWidgets) slideshow.on('afterShowSlide', function (slide) {
window.dispatchEvent(new Event('resize'));
});
(function() {
var d = document, 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);
})();</script>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {
skipTags: ['script', 'noscript', 'style', 'textarea', 'pre']
}
});
</script>
<!-- dynamically load mathjax for compatibility with self-contained -->
<script>
(function () {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://cdn.bootcss.com/mathjax/2.7.1/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>