-
Notifications
You must be signed in to change notification settings - Fork 2
/
rladies-spatial-data.Rmd
431 lines (282 loc) · 9.08 KB
/
rladies-spatial-data.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
---
title: "Introduction to Spatial Data Analysis and Mapping in R"
subtitle: "🌎 🗺<br/>with sf and tmap"
author: "Angela Li <br> @CivicAngela <br> Center for Spatial Data Science, UChicago <br> Slides available at http://bit.ly/rladies-spatial"
date: "2018-04-28"
output:
xaringan::moon_reader:
css: ["default", "rladies", "rladies-fonts"]
lib_dir: libs
nature:
highlightStyle: github
highlightLines: true
countIncrementalSlides: false
---
```{r setup, include=FALSE}
options(htmltools.dir.version = FALSE)
```
# Three parts to this talk:
## 1. Why spatial data in R?
## 2. A quick tutorial
## 3. Some thoughts on the future of #rspatial
---
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 eval=FALSE, tidy=FALSE}
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 eval=FALSE, tidy=FALSE}
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!)
---
# Make your first map (1)
```{r warning=FALSE}
# Load package
library(sf)
# Read in shapefile
chi <- st_read("data/Neighborhoods_2012b.shp")
```
---
# Make your first map (2)
```{r}
# Map it using base R: just shape outlines
plot(st_geometry(chi))
```
---
# Make your first map (3)
```{r}
# This maps all the attributes
plot(chi)
```
---
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")
```
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 by neighborhood!
```{r}
# Check what variables we have
names(chi2)
```
---
```{r}
# Map population by neighborhood
plot(chi2["Pop2014"])
```
---
# Use `tmap` to make a prettier map
```{r eval=FALSE}
library(tmap)
tm_shape(chi2) +
tm_fill("Pop2014", palette = "Purples",
title = "Population by Neighborhood, 2014")
```
---
```{r echo=FALSE}
library(tmap)
tm_shape(chi2) +
tm_fill("Pop2014", palette = "Purples",
title = "Population by Neighborhood, 2014")
```
---
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 warning=FALSE}
groceries <- st_read("data/groceries.shp")
```
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 warning=FALSE}
# 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 eval=FALSE}
# Plot both
tm_shape(chi2) +
tm_borders() +
tm_fill("Pop2014", palette = "Purples",
title = "Population by Neighborhood, 2014") +
tm_shape(groceries) +
tm_dots(title = "Groceries", size = 0.1, col = "black")
```
---
```{r echo=FALSE}
# Plot both
tm_shape(chi2) +
tm_borders() +
tm_fill("Pop2014", palette = "Purples",
title = "Population by Neighborhood, 2014") +
tm_shape(groceries) +
tm_dots(title = "Groceries", size = 0.1, col = "black")
```
---
class: inverse, center, middle
# You can also use dplyr to perform analysis!
---
# Which neighborhoods in Chicago have the most grocery stores?
```{r message=FALSE}
library(dplyr)
chi2 %>%
st_join(groceries, .) %>%
group_by(community) %>%
tally() %>%
arrange(desc(n))
```
---
# More advanced spatial analysis involves buffers, distance, intersections, etc.
Code from my thesis:
```{r eval=FALSE}
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 words on the future of #rspatial
---
class: inverse, middle, center
# IT NEEDS MORE WOMEN
---
# 1. Submitting issues
![](images/github-issue.png)
---
# 2. Building communities
![](images/rspatial-slack.png)
---
class: center, inverse, middle
# 3. Getting our voices out there!
## Stay tuned for more...
---
class: center, middle
# Thanks!
Slides created via the R package [xaringan](https://github.com/yihui/xaringan) by [Yihui Xie](https://twitter.com/xieyihui?lang=en) with the [Rladies](https://alison.rbind.io/post/r-ladies-slides/) theme by [Alison Hill](https://twitter.com/apreshill).
Slides available at <font style="text-transform: lowercase;"><http://bit.ly/rladies-spatial></font> <br>
Contact me at @[CivicAngela](https://twitter.com/CivicAngela), [email protected]