Debian Codegraph @

vignettes/sp_gallery.Rmd

raw
1 ---
2 title: "sp Gallery"
3 output:
4 html_document:
5 toc: true
6 toc_float:
7 collapsed: false
8 smooth_scroll: false
9 toc_depth: 2
10 vignette: >
11 %\VignetteIndexEntry{sp map gallery}
12 %\VignetteEngine{knitr::rmarkdown}
13 %\VignetteEncoding{UTF-8}
14 ---
15
16 # Plotting maps with `sp`
17
18 This document shows example images created with objects
19 represented by one of the classes for spatial data in
20 packages sp.
21
22 ## Loading data and packages
23
24 The Meuse data set is loaded using a demo script in package `sp`,
25 ```{r}
26 library(sp)
27 demo(meuse, ask = FALSE, echo = FALSE) # loads the meuse data sets
28 class(meuse)
29 ```
30
31 The North Carolina SIDS (sudden infant death syndrome) data set
32 is available from package `sf`, and is loaded by
33
34 ```{r}
35 library(sf)
36 nc <- as(st_read(system.file("gpkg/nc.gpkg", package="sf")), "Spatial")
37 ```
38
39 ## Using base plot
40
41 The basic `plot` command on a `Spatial` object gives just the geometry, without axes:
42
43 ```{r}
44 plot(meuse)
45 ```
46
47 axes can be added when `axes=TRUE` is given; plot elements can be added incrementally:
48
49 ```{r}
50 plot(meuse, pch = 1, cex = sqrt(meuse$zinc)/12, axes = TRUE)
51 v = c(100,200,400,800,1600)
52 legend("topleft", legend = v, pch = 1, pt.cex = sqrt(v)/12)
53 plot(meuse.riv, add = TRUE, col = grey(.9, alpha = .5))
54 ```
55
56 For local projection systems, such as in this case
57
58 ```{r}
59 proj4string(meuse)
60 ```
61
62 the aspect ratio is set to 1, to make sure that one unit north
63 equals one unit east. Even if the data are in long/lat degrees,
64 an aspect ratio is chosen such that in the middle of the plot one
65 unit north approximates one unit east. For small regions, this works
66 pretty well; also note the degree symbols in the axes tic marks:
67
68 ```{r, fig.height=8}
69 crs.longlat = CRS("+init=epsg:4326")
70 meuse.longlat = spTransform(meuse, crs.longlat)
71 plot(meuse.longlat, axes = TRUE)
72 ```
73
74 which looks different from the plot where one degree north (latitude) equals one
75 degree east (longitude):
76
77 ```{r}
78 par(mar = rep(0,4))
79 plot(meuse.longlat, asp = 1)
80 ```
81
82 ## Graticules
83
84 Instead of axes with ticks and tick marks, maps often have
85 graticules, a grid with constant longitude and latitude lines.
86 `sp` provides several helper functions to add graticules, either
87 in the local reference system, or in long/lat. Here is an
88 example of the local reference system:
89
90 ```{r, fig.height=7.5}
91 par(mar = c(0, 0, 1, 0))
92 library(methods) # as
93 plot(as(meuse, "Spatial"), expandBB = c(.05, 0, 0, 0))
94 plot(gridlines(meuse), add = TRUE, col = grey(.8))
95 plot(meuse, add = TRUE)
96 text(labels(gridlines(meuse)), col = grey(.7))
97 title("default gridlines with Meuse projected data")
98 ```
99
100 ```{r}
101 par(mar = c(0, 0, 1, 0))
102 grd <- gridlines(meuse.longlat)
103 grd_x <- spTransform(grd, CRS(proj4string(meuse)))
104 plot(as(meuse, "Spatial"), expandBB = c(.05, 0, 0, 0))
105 plot(grd_x, add=TRUE, col = grey(.8))
106 plot(meuse, add = TRUE)
107 text(labels(grd_x, crs.longlat), col = grey(.7))
108 title("longitude latitude gridlines and labels")
109 ```
110
111 These lines look pretty straight, because it concerns a small area.
112 For
113
114 ```{r}
115 # demonstrate axis labels with angle, both sides:
116
117 maps2sp = function(xlim, ylim, l.out = 100, clip = TRUE) {
118 stopifnot(require(maps))
119 m = map(xlim = xlim, ylim = ylim, plot = FALSE, fill = TRUE)
120 as(st_as_sf(m), "Spatial")
121 }
122 par(mar = c(0, 0, 1, 0))
123 m = maps2sp(c(-100,-20), c(10,55))
124 sp = SpatialPoints(rbind(c(-101,9), c(-101,55), c(-19,9), c(-19,55)), CRS("+init=epsg:4326"))
125 laea = CRS("+proj=laea +lat_0=30 +lon_0=-40")
126 m.laea = spTransform(m, laea)
127 sp.laea = spTransform(sp, laea)
128 plot(as(m.laea, "Spatial"), expandBB = c(.1, 0.05, .1, .1))
129 plot(m.laea, col = grey(.8), add = TRUE)
130 gl = gridlines(sp, easts = c(-100,-80,-60,-40,-20), norths = c(20,30,40,50))
131 gl.laea = spTransform(gl, laea)
132 plot(gl.laea, add = TRUE)
133 text(labels(gl.laea, crs.longlat))
134 text(labels(gl.laea, crs.longlat, side = 3:4), col = 'red')
135 title("curved text label demo")
136
137 # polar:
138 par(mar = c(0, 0, 1, 0))
139 pts=SpatialPoints(rbind(c(-180,-70),c(0,-70),c(180,-89),c(180,-70)), CRS("+init=epsg:4326"))
140 gl = gridlines(pts, easts = seq(-180,180,20), ndiscr = 100)
141 polar = CRS("+init=epsg:3031")
142 plot(spTransform(pts, polar), expandBB = c(.05, 0, .05, 0))
143 gl.polar = spTransform(gl, polar)
144 lines(gl.polar)
145 l = labels(gl.polar, crs.longlat, side = 3)
146 l$pos = NULL # pos is too simple, use adj:
147 text(l, adj = c(0.5, -0.5), cex = .8)
148 l = labels(gl.polar, crs.longlat, side = 4)
149 l$srt = 0 # otherwise they end up upside-down
150 text(l, cex = .8)
151 title("grid line labels on polar projection, epsg 3031")
152
153 par(mar = c(0, 0, 1, 0))
154 m = maps2sp(xlim = c(-180,180), ylim = c(-90,-70), clip = FALSE)
155 gl = gridlines(m, easts = seq(-180,180,20))
156 polar = CRS("+init=epsg:3031")
157 gl.polar = spTransform(gl, polar)
158 plot(as(gl.polar, "Spatial"), expandBB = c(.05, 0, .05, 0))
159 plot(gl.polar, add = TRUE)
160 plot(spTransform(m, polar), add = TRUE, col = grey(0.8, 0.8))
161 l = labels(gl.polar, crs.longlat, side = 3)
162 # pos is too simple here, use adj:
163 l$pos = NULL
164 text(l, adj = c(0.5, -0.3), cex = .8)
165 l = labels(gl.polar, crs.longlat, side = 2)
166 l$srt = 0 # otherwise they are upside-down
167 text(l, cex = .8)
168 title("grid line labels on polar projection, epsg 3031")
169
170 ```
171
172 ## Other spatial objects in base plot
173
174 The following plot shows polygons with county name as labels at
175 their center point:
176
177 ```{r}
178 par(mar = c(0, 0, 1, 0))
179 plot(nc)
180 invisible(text(coordinates(nc), labels=as.character(nc$NAME), cex=0.4))
181 ```
182
183 This plot of a `SpatialPolygonsDataFrame` uses grey shades:
184
185 ```{r}
186 names(nc)
187 rrt <- nc$SID74/nc$BIR74
188 brks <- quantile(rrt, seq(0,1,1/7))
189 cols <- grey((length(brks):2)/length(brks))
190 dens <- (2:length(brks))*3
191 par(mar = c(0, 0, 1, 0))
192 plot(nc, col=cols[findInterval(rrt, brks, all.inside=TRUE)])
193 ```
194
195 The following plot shows a `SpatialPolygonsDataFrame`, using line densities
196
197 ```{r}
198 rrt <- nc$SID74/nc$BIR74
199 brks <- quantile(rrt, seq(0,1,1/7))
200 cols <- grey((length(brks):2)/length(brks))
201 dens <- (2:length(brks))*3
202 par(mar = rep(0,4))
203 plot(nc, density=dens[findInterval(rrt, brks, all.inside=TRUE)])
204 ```
205
206 Plot/image of a grid file, using base plot methods:
207
208 ```{r}
209 image(meuse.grid)
210 ```
211
212 ```{r}
213 plot(meuse.grid["dist"])
214 points(meuse, col = 'green')
215 ```
216
217 ```{r}
218 plot(meuse.grid["dist"], zlim = c(0,1))
219 plot(geometry(meuse.grid), add = TRUE, col = grey(.8))
220 ```
221
222 Read
223 [this](https://r-spatial.org/r/2016/03/08/plotting-spatial-grids.html)
224 blog post to find out more about the options available (and
225 limitations) for plotting gridded data with base plot methods in sp.
226
227 ## using lattice plot (spplot)
228
229 The following plot colours points with a legend in the plotting area and adds scales:
230
231 ```{r}
232 spplot(meuse, "zinc", do.log = TRUE,
233 key.space=list(x = 0.1, y = 0.95, corner = c(0, 1)),
234 scales=list(draw = TRUE))
235 ```
236
237 The following plot has coloured points plot with legend in plotting area and scales;
238 it has a non-default number of cuts with user-supplied legend entries:
239 ```{r}
240 spplot(meuse, "zinc", do.log = TRUE,
241 key.space=list(x=0.2,y=0.9,corner=c(0,1)),
242 scales=list(draw = TRUE), cuts = 3,
243 legendEntries = c("low", "intermediate", "high"))
244 ```
245
246 The following plot adds a scale bar and north arrow:
247
248 ```{r}
249 scale = list("SpatialPolygonsRescale", layout.scale.bar(),
250 offset = c(178600,332490), scale = 500, fill=c("transparent","black"))
251 text1 = list("sp.text", c(178600,332590), "0")
252 text2 = list("sp.text", c(179100,332590), "500 m")
253 arrow = list("SpatialPolygonsRescale", layout.north.arrow(),
254 offset = c(178750,332000), scale = 400)
255 spplot(meuse, "zinc", do.log=T,
256 key.space=list(x=0.1,y=0.93,corner=c(0,1)),
257 sp.layout=list(scale,text1,text2,arrow),
258 main = "Zinc (top soil)")
259 ```
260
261 The following plot has north arrow and text outside panels
262
263 ```{r}
264 rv = list("sp.polygons", meuse.riv, fill = "lightblue")
265 scale = list("SpatialPolygonsRescale", layout.scale.bar(),
266 offset = c(180500,329800), scale = 500, fill=c("transparent","black"), which = 1)
267 text1 = list("sp.text", c(180500,329900), "0", which = 1)
268 text2 = list("sp.text", c(181000,329900), "500 m", which = 1)
269 arrow = list("SpatialPolygonsRescale", layout.north.arrow(),
270 offset = c(178750,332500), scale = 400)
271 spplot(meuse["zinc"], do.log = TRUE,
272 key.space = "bottom",
273 sp.layout = list(rv, scale, text1, text2),
274 main = "Zinc (top soil)",
275 legend = list(right = list(fun = mapLegendGrob(layout.north.arrow()))))
276 ```
277
278 The same plot; north arrow now inside panel, with custom panel function instead of sp.layout
279
280 ```{r}
281 spplot(meuse, "zinc", panel = function(x, y, ...) {
282 sp.polygons(meuse.riv, fill = "lightblue")
283 SpatialPolygonsRescale(layout.scale.bar(), offset = c(179900,329600),
284 scale = 500, fill=c("transparent","black"))
285 sp.text(c(179900,329700), "0")
286 sp.text(c(180400,329700), "500 m")
287 SpatialPolygonsRescale(layout.north.arrow(),
288 offset = c(178750,332500), scale = 400)
289 panel.pointsplot(x, y, ...)
290 },
291 do.log = TRUE, cuts = 7,
292 key.space = list(x = 0.1, y = 0.93, corner = c(0,1)),
293 main = "Top soil zinc concentration (ppm)")
294 ```
295
296 A multi-panel plot, scales + north arrow only in last plot: using
297 the `which` argument in a layout component (if `which=4` was set
298 as list component of sp.layout, the river would as well be drawn
299 only in that (last) panel)
300
301 ```{r}
302 rv = list("sp.polygons", meuse.riv, fill = "lightblue")
303 scale = list("SpatialPolygonsRescale", layout.scale.bar(),
304 offset = c(180500,329800), scale = 500, fill=c("transparent","black"), which = 4)
305 text1 = list("sp.text", c(180500,329900), "0", cex = .5, which = 4)
306 text2 = list("sp.text", c(181000,329900), "500 m", cex = .5, which = 4)
307 arrow = list("SpatialPolygonsRescale", layout.north.arrow(),
308 offset = c(181300,329800),
309 scale = 400, which = 4)
310 cuts = c(.2,.5,1,2,5,10,20,50,100,200,500,1000,2000)
311 spplot(meuse, c("cadmium", "copper", "lead", "zinc"), do.log = TRUE,
312 key.space = "right", as.table = TRUE,
313 sp.layout=list(rv, scale, text1, text2, arrow), # note that rv is up front!
314 main = "Heavy metals (top soil), ppm", cex = .7, cuts = cuts)
315 ```
316
317 Comparing four kriging varieties in a multi-panel plot with shared scale:
318
319 ```{r}
320 rv = list("sp.polygons", meuse.riv, fill = "blue", alpha = 0.1)
321 pts = list("sp.points", meuse, pch = 3, col = "grey", alpha = .5)
322 text1 = list("sp.text", c(180500,329900), "0", cex = .5, which = 4)
323 text2 = list("sp.text", c(181000,329900), "500 m", cex = .5, which = 4)
324 scale = list("SpatialPolygonsRescale", layout.scale.bar(),
325 offset = c(180500,329800), scale = 500, fill=c("transparent","black"), which = 4)
326 library(gstat)
327 v.ok = variogram(log(zinc)~1, meuse)
328 ok.model = fit.variogram(v.ok, vgm(1, "Exp", 500, 1))
329 # plot(v.ok, ok.model, main = "ordinary kriging")
330 v.uk = variogram(log(zinc)~sqrt(dist), meuse)
331 uk.model = fit.variogram(v.uk, vgm(1, "Exp", 300, 1))
332 # plot(v.uk, uk.model, main = "universal kriging")
333 meuse[["ff"]] = factor(meuse[["ffreq"]])
334 meuse.grid[["ff"]] = factor(meuse.grid[["ffreq"]])
335 v.sk = variogram(log(zinc)~ff, meuse)
336 sk.model = fit.variogram(v.sk, vgm(1, "Exp", 300, 1))
337 # plot(v.sk, sk.model, main = "stratified kriging")
338 zn.ok = krige(log(zinc)~1, meuse, meuse.grid, model = ok.model, debug.level = 0)
339 zn.uk = krige(log(zinc)~sqrt(dist), meuse, meuse.grid, model = uk.model, debug.level = 0)
340 zn.sk = krige(log(zinc)~ff, meuse, meuse.grid, model = sk.model, debug.level = 0)
341 zn.id = krige(log(zinc)~1, meuse, meuse.grid, debug.level = 0)
342
343 zn = zn.ok
344 zn[["a"]] = zn.ok[["var1.pred"]]
345 zn[["b"]] = zn.uk[["var1.pred"]]
346 zn[["c"]] = zn.sk[["var1.pred"]]
347 zn[["d"]] = zn.id[["var1.pred"]]
348 spplot(zn, c("a", "b", "c", "d"),
349 names.attr = c("ordinary kriging", "universal kriging with dist to river",
350 "stratified kriging with flood freq", "inverse distance"),
351 as.table = TRUE, main = "log-zinc interpolation",
352 sp.layout = list(rv, scale, text1, text2)
353 )
354 ```
355
356 Reuse these results; universal kriging standard errors; grid plot
357 with point locations and polygon (river):
358
359 ```{r}
360 rv = list("sp.polygons", meuse.riv, fill = "blue", alpha = 0.1)
361 pts = list("sp.points", meuse, pch = 3, col = "grey", alpha = .7)
362 spplot(zn.uk, "var1.pred",
363 sp.layout = list(rv, scale, text1, text2, pts),
364 main = "log(zinc); universal kriging using sqrt(dist to Meuse)")
365 zn.uk[["se"]] = sqrt(zn.uk[["var1.var"]])
366 spplot(zn.uk, "se", sp.layout = list(rv, pts),
367 main = "log(zinc); universal kriging standard errors")
368 ```
369
370 ```{r}
371 arrow = list("SpatialPolygonsRescale", layout.north.arrow(),
372 offset = c(-76,34), scale = 0.5, which = 2)
373 spplot(nc, c("SID74", "SID79"), names.attr = c("1974","1979"),
374 colorkey=list(space="bottom"), scales = list(draw = TRUE),
375 main = "SIDS (sudden infant death syndrome) in North Carolina",
376 sp.layout = list(arrow), as.table = TRUE)
377 ```
378
379 ```{r}
380 arrow = list("SpatialPolygonsRescale", layout.north.arrow(),
381 offset = c(-76,34), scale = 0.5, which = 2)
382 #scale = list("SpatialPolygonsRescale", layout.scale.bar(),
383 # offset = c(-77.5,34), scale = 1, fill=c("transparent","black"), which = 2)
384 #text1 = list("sp.text", c(-77.5,34.15), "0", which = 2)
385 #text2 = list("sp.text", c(-76.5,34.15), "1 degree", which = 2)
386 # create a fake lines data set:
387 ## multi-panel plot with coloured lines: North Carolina SIDS
388 spplot(nc, c("SID74","SID79"), names.attr = c("1974","1979"),
389 colorkey=list(space="bottom"),
390 main = "SIDS (sudden infant death syndrome) in North Carolina",
391 sp.layout = arrow, as.table = TRUE)
392 ```
393
394 Bubble plots for cadmium and zinc:
395
396 ```{r}
397 b1 = bubble(meuse, "cadmium", maxsize = 1.5, main = "cadmium concentrations (ppm)",
398 key.entries = 2^(-1:4))
399 b2 = bubble(meuse, "zinc", maxsize = 1.5, main = "zinc concentrations (ppm)",
400 key.entries = 100 * 2^(0:4))
401 print(b1, split = c(1,1,2,1), more = TRUE)
402 print(b2, split = c(2,1,2,1), more = FALSE)
403 ```
404
405 Factor variables using `spplot`:
406
407 ```{r}
408 # create two dummy factor variables, with equal labels:
409 set.seed(31)
410 nc$f = factor(sample(1:5, 100,replace = TRUE),labels=letters[1:5])
411 nc$g = factor(sample(1:5, 100,replace = TRUE),labels=letters[1:5])
412 library(RColorBrewer)
413 ## Two (dummy) factor variables shown with qualitative colour ramp; degrees in axes
414 spplot(nc, c("f","g"), col.regions=brewer.pal(5, "Set3"), scales=list(draw = TRUE))
415
416 ```
417
418 ## maps using ggplot2
419
420 (it is recommended to migrate to `sf`, and use `geom_sf()` for this)
421
422 ## Interactive maps: leaflet, mapview
423
424 R packages leaflet and mapview provide interactive, browser-based
425 maps building upon the leaflet javascript library. Example with
426 points, grid and polygons follow:
427
428 ```{r, results="markup"}
429 library(mapview)
430 mapview(meuse, zcol = c("zinc", "lead"), legend = TRUE)
431 ```
432
433 ```{r, results="markup"}
434 mapview(meuse.grid, zcol = c("soil", "dist"), legend = TRUE)
435 ```
436
437 ```{r, results="markup"}
438 mapview(nc, zcol = c("SID74", "SID79"), alpha.regions = 1.0, legend = TRUE)
439 ```
440
441 Mapview also allows grids of view that are synced
442 ```{r, results="markup",eval=FALSE}
443 m1 <- mapview(meuse, zcol = "soil", burst = TRUE, legend = TRUE)
444 m2 <- mapview(meuse, zcol = "lead", legend = TRUE)
445 m3 <- mapview(meuse, zcol = "landuse", map.types = "Esri.WorldImagery", legend = TRUE)
446 m4 <- mapview(meuse, zcol = "dist.m", legend = TRUE)
447 sync(m1, m2, m3, m4) # 4 panels synchronised
448 # latticeView(m1, m2, m3, m4) # 4 panels
449 ```
450
451 more examples are found [here](https://environmentalinformatics-marburg.github.io/web-presentations/20150723_mapView.html).
452
453 ## SessionInfo
454
455 ```{r}
456 sessionInfo()
457 ```