Debian Codegraph @

R/spplot.R

raw
1 setMethod("sppanel", "SpatialPolygons",
2 function(obj, col = 1, fill = "transparent", ...) {
3 if (is.character(obj))
4 obj = get(obj)
5 if (!is(obj, "SpatialPolygons"))
6 stop(paste(
7 "object extending class SpatialPolygons expected; got class",
8 class(obj)))
9 else
10 obj = as(obj, "SpatialPolygons")
11 if (get_Polypath()) {
12 lo = length(obj)
13 obj = as(as(obj, "SpatialLines"), "SpatialPointsDataFrame")
14 cc = coordinates(obj)
15 #id = as.numeric(obj$Line.NR)
16 id = as.numeric(obj$Lines.NR * max(obj$Line.NR) + (obj$Line.NR - 1))
17 if (length(fill) > 1 || length(col) > 1) {
18 fill = rep(fill, length.out = lo)
19 col = rep(col, length.out = lo)
20 for (i in 1:lo) {
21 sel = obj$Lines.NR == i
22 grid.path(cc[sel,1], cc[sel,2], id[sel],
23 default.units = "native",
24 gp = gpar(col = col[i], fill = fill[i], ...))
25 }
26 } else
27 grid.path(cc[,1], cc[,2], id, default.units = "native",
28 gp = gpar(col = col, fill = fill, ...))
29 } else {
30 sp.polygon3 = function(x, col, fill, ...) {
31 cc = slot(x, "coords")
32 grid.polygon(cc[,1], cc[,2], default.units = "native",
33 gp = gpar(col = col, fill = fill, ...))
34 panel.lines(cc, col = col, ...)
35 }
36 pls = slot(obj, "polygons")
37 pO <- slot(obj, "plotOrder")
38 if (length(fill) != length(pO))
39 fill <- rep(fill[1], length(pO))
40 for (i in pO) {
41 Srs <- slot(pls[[i]], "Polygons")
42 pOi <- slot(pls[[i]], "plotOrder")
43 for (j in pOi)
44 sp.polygon3(Srs[[j]], col = col, fill = fill[i], ...)
45 }
46 }
47 })
48
49 # backward compatibility:
50 sp.polygons = function(obj, col = 1, fill = "transparent",...)
51 sppanel(obj, col = col, fill = fill, ...)
52
53 setMethod("sppanel", "SpatialLines",
54 function (obj, col = 1, ...) {
55 ## contributed by Josh O'Brien, Mar 15, 2015
56 lo <- length(obj@lines)
57 col <- rep(col, length.out = lo)
58 lapply(seq_len(lo), function(ii) sppanel(obj@lines[[ii]], col = col[ii], ...))
59 })
60
61 setMethod("sppanel", "Lines",
62 function (obj, col = 1, ...) lapply(obj@Lines, sppanel, col = col, ...))
63
64 setMethod("sppanel", "Line",
65 function (obj, col = 1, ...) panel.lines(coordinates(obj), col = col, ...))
66
67 # backward compatibility:
68 sp.lines = function(obj, col = 1,...) sppanel(obj, col = col,...)
69
70 setMethod("sppanel", "SpatialPoints",
71 function(obj, pch = 3, ...)
72 panel.points(coordinates(obj), pch = pch, ...))
73 # backward compatibility:
74 sp.points = function(obj, pch=3, ...) sppanel(obj, pch = pch, ...)
75
76 sp.grid = function(obj, col = 1, alpha = 1, ..., at = pretty(obj[[1]]),
77 col.regions = col) {
78 xy = coordinates(obj)
79 if (length(col) > 1 && ("data" %in% slotNames(obj))) {
80 z = obj[[1]]
81 if (is.factor(z))
82 col = col[z]
83 else # cut:
84 col = level.colors(z, at, col.regions, colors = TRUE)
85 }
86 gt = as(getGridTopology(obj), "data.frame")
87 grid.rect(x = xy[,1], y = xy[,2], width = gt$cellsize[1],
88 height = gt$cellsize[2], default.units = "native",
89 gp = gpar(fill = col, col = NA, alpha = alpha))
90 }
91 setMethod("sppanel", "SpatialPixels", sp.grid)
92 setMethod("sppanel", "SpatialGrid", sp.grid)
93
94 sp.text = function(loc, txt, ...) {
95 if (!is.numeric(loc))
96 stop("loc (first argument) should be numeric, indicating text locations")
97 if (length(loc) == 2)
98 panel.text(loc[1], loc[2], txt, ...)
99 else if (is.matrix(loc) && ncol(loc) == 2 && nrow(loc) == length(txt))
100 panel.text(loc[,1], loc[,2], txt, ...)
101 else
102 stop("loc and txt have non-matching dimensions")
103 }
104 setMethod("sppanel", "character", function(obj,txt, ...) sp.text(obj, txt, ...))
105
106 sp.panel.layout = function(lst, p.number, ...) { # now obsolete...
107 .Deprecated("sppanel")
108 sp.panel0 = function(x, first = FALSE, ...) {
109 if (inherits(x, "list")) {
110 if (!is.null(x$which) && is.na(match(p.number, x$which)))
111 return()
112 # print(paste(class(x), "first val", first, "first obj", x$first))
113 if (!is.null(x$first)) {
114 if (x$first == first)
115 do.call(x[[1]], x[2:length(x)])
116 } else if (!first)
117 do.call(x[[1]], x[2:length(x)])
118 }
119 }
120 if (!is.null(lst$which) && is.na(match(p.number, lst$which)))
121 return()
122 else
123 lst$which = NULL
124 if (is.null(lst))
125 return()
126 if (inherits(lst, "list")) {
127 if (inherits(lst[[1]], "list"))
128 lapply(lst, sp.panel0, ...)
129 else
130 sp.panel0(lst, ...)
131 } else
132 stop(paste("expected object of class list; got object of class", class(lst)))
133 }
134
135 setMethod("sppanel", "NULL", function(obj,...) { })
136
137 sppanelList = function(obj, p.number, first, ...) {
138 missingFirst = missing(first)
139 if (length(obj) == 1 & is.null(obj[[1]]))
140 return()
141 if (!is.null(obj$which) && is.na(match(p.number, obj$which)))
142 return() # false panel
143 else
144 obj$which = NULL # continue: either all panels, or right panel
145 if (is.list(obj[[1]])) # list-of-lists, recurse:
146 return(lapply(obj, sppanel, p.number = p.number, first = first, ...))
147 opaque = function(x) (is(x, "SpatialPolygons") || is(x, "SpatialGrid") || is(x, "SpatialPixels"))
148 if (is.character(obj[[1]]) || is.function(obj[[1]])) {
149 if (is.null(obj$first))
150 obj$first = opaque(obj[[2]]) # default: grids/polygons behind, rest front
151 if (missingFirst) # meaning: do plot it
152 first = obj$first
153 if (obj$first == first) {
154 obj$first = NULL
155 do.call(obj[[1]], obj[-1], ...)
156 }
157 } else {
158 sp = sapply(obj, is, "Spatial")
159 stopifnot(any(sp))
160 lapply(obj[sp], function(x) {
161 if (missingFirst || identical(obj$first, first) || opaque(x) == first)
162 do.call(sppanel, append(x, obj[!sp]), ...)
163 })
164 }
165 }
166 setMethod("sppanel", "list", sppanelList)
167
168 getFormulaLevelplot = function(sdf, zcol) {
169 if (length(zcol) > 1)
170 as.formula(paste("z~", paste(dimnames(coordinates(sdf))[[2]],
171 collapse = "+"), "|name"))
172 else {
173 if (!is.character(zcol))
174 zcol = names(sdf)[zcol]
175 as.formula(paste(zcol, "~", paste(dimnames(coordinates(sdf))[[2]],
176 collapse = "+")))
177 }
178 }
179
180 spplot.grid = function(obj, zcol = names(obj), ..., names.attr,
181 scales = list(draw = FALSE), xlab = NULL, ylab = NULL,
182 aspect = mapasp(obj,xlim,ylim), panel = panel.gridplot, sp.layout = NULL, formula,
183 xlim = bbox(obj)[1,], ylim = bbox(obj)[2,], checkEmptyRC = TRUE,
184 col.regions = get_col_regions()) {
185 if (is.null(zcol)) stop("no names method for object")
186 if (checkEmptyRC)
187 sdf = addNAemptyRowsCols(obj) # returns SpatialPointsDataFrame
188 else
189 sdf = as(obj, "SpatialPointsDataFrame")
190 if (missing(formula))
191 formula = getFormulaLevelplot(sdf, zcol)
192 if (length(zcol) > 1) {
193 sdf = spmap.to.lev(sdf, zcol = zcol, names.attr = names.attr)
194 zcol2 = "z"
195 } else
196 zcol2 = zcol
197 if (exists("panel.levelplot.raster")) {
198 opan <- lattice.options("panel.levelplot")[[1]]
199 lattice.options("panel.levelplot"="panel.levelplot.raster")
200 # cat("using raster panel\n")
201 }
202 scales = longlat.scales(obj, scales, xlim, ylim)
203 args = append(list(formula, data = as(sdf, "data.frame"),
204 aspect = aspect, panel = panel, xlab = xlab, ylab = ylab, scales = scales,
205 sp.layout = sp.layout, xlim = xlim, ylim = ylim, col.regions = col.regions),
206 list(...))
207 # deal with factor variables:
208 if (all(unlist(lapply(obj@data[zcol], is.factor)))) {
209 #if (!is.null(args$col.regions) &&
210 # nlevels(obj@data[[zcol[1]]]) != length(args$col.regions))
211 # stop("length of col.regions should match number of factor levels")
212 args$data[[zcol2]] = as.numeric(args$data[[zcol2]])
213 if (is.null(args$colorkey) || (is.logical(args$colorkey) && args$colorkey)
214 || (is.list(args$colorkey) && is.null(args$colorkey$at) &&
215 is.null(args$colorkey$labels))) {
216 if (!is.list(args$colorkey))
217 args$colorkey = list()
218 ck = args$colorkey
219 args$colorkey = NULL
220 args = append(args, colorkey.factor(obj[[zcol[1]]], ck))
221 } else
222 args = append(args, colorkey.factor(obj[[zcol[1]]], ck, FALSE))
223 }
224 ret = do.call(levelplot, args)
225 if (exists("panel.levelplot.raster"))
226 lattice.options("panel.levelplot" = opan)
227 ret
228 }
229
230 setMethod("spplot", signature("SpatialPixelsDataFrame"), spplot.grid)
231 setMethod("spplot", signature("SpatialGridDataFrame"),
232 function(obj, ...) spplot.grid(as(obj, "SpatialPixelsDataFrame"), ...))
233
234 spplot.polygons = function(obj, zcol = names(obj), ..., names.attr,
235 scales = list(draw = FALSE), xlab = NULL, ylab = NULL,
236 aspect = mapasp(obj,xlim,ylim),
237 panel = panel.polygonsplot, sp.layout = NULL, formula,
238 xlim = bbox(obj)[1,], ylim = bbox(obj)[2,],
239 col.regions = get_col_regions()) {
240
241 if (is.null(zcol)) stop("no names method for object")
242 sdf = as(obj, "data.frame")
243 if (is(obj, "SpatialPolygonsDataFrame"))
244 labpts = coordinates(obj)
245 else {
246 # get first points of each lines object:
247 n = length(obj@lines)
248 labpts = matrix(unlist(lapply(obj@lines, function(x)
249 lapply(x@Lines[1], function(x) coordinates(x)[1,]))),
250 n, 2, byrow=TRUE)
251 }
252 dimnames(labpts)[[2]] = c("xlabelpoint", "ylabelpoint")
253 sdf = as.data.frame(cbind(labpts, sdf))
254 coordinates(sdf) = c("xlabelpoint", "ylabelpoint")
255 if (missing(formula))
256 formula = getFormulaLevelplot(sdf, zcol)
257 if (length(zcol) > 1) {
258 sdf = spmap.to.lev(sdf, zcol = zcol, names.attr = names.attr)
259 zcol2 = "z"
260 } else
261 zcol2 = zcol
262 if (is(obj, "SpatialPolygonsDataFrame"))
263 grid.polygons = as(obj, "SpatialPolygons")
264 else
265 grid.polygons = as(obj, "SpatialLines")
266 scales = longlat.scales(obj, scales, xlim, ylim)
267
268 args = append(list(formula, data = as(sdf, "data.frame"),
269 aspect = aspect, grid.polygons = grid.polygons, panel =
270 panel, xlab = xlab, ylab = ylab, scales = scales,
271 sp.layout = sp.layout, xlim = xlim, ylim = ylim,
272 col.regions = col.regions), list(...))
273 if (all(unlist(lapply(obj@data[zcol], is.factor)))) {
274 #if (!is.null(args$col.regions) &&
275 # nlevels(obj@data[[zcol[1]]]) != length(args$col.regions))
276 # stop("length of col.regions should match number of factor levels")
277 args$data[[zcol2]] = as.numeric(args$data[[zcol2]])
278 if (is.null(args$colorkey)
279 || (is.logical(args$colorkey) && args$colorkey)
280 || (is.list(args$colorkey) && is.null(args$colorkey$at) &&
281 is.null(args$colorkey$labels))) {
282 if (!is.list(args$colorkey))
283 args$colorkey = list()
284 ck = args$colorkey
285 args$colorkey = NULL
286 args = append(args, colorkey.factor(obj[[zcol[1]]], ck))
287 } else
288 args = append(args, colorkey.factor(obj[[zcol[1]]], ck, FALSE))
289 }
290 do.call(levelplot, args)
291 }
292
293 setMethod("spplot", signature("SpatialPolygonsDataFrame"), spplot.polygons)
294 setMethod("spplot", signature("SpatialLinesDataFrame"), spplot.polygons)
295
296 spplot.points = function(obj, zcol = names(obj), ..., names.attr,
297 scales = list(draw = FALSE), xlab = NULL, ylab = NULL,
298 aspect = mapasp(obj,xlim,ylim), panel = panel.pointsplot,
299 sp.layout = NULL, identify = FALSE, formula,
300 xlim = bbexpand(bbox(obj)[1,], 0.04),
301 ylim = bbexpand(bbox(obj)[2,], 0.04),
302 edge.col = "transparent", colorkey = FALSE,
303 col.regions = get_col_regions())
304 {
305
306 if (is.null(zcol)) stop("no names method for object")
307 dots = list(...)
308 sdf = obj
309 if (!is.character(zcol))
310 zcol = names(sdf)[zcol]
311 # create formula:
312 if (missing(formula)) {
313 if (length(zcol) > 1) {
314 formula = as.formula(paste(paste(dimnames(coordinates(sdf))[[2]][2:1],
315 collapse = "~"), "|name"))
316 sdf = spmap.to.lev(sdf, zcol = zcol, names.attr = names.attr)
317 } else {
318 if (!is.character(zcol))
319 zcol = names(sdf)[zcol]
320 ccn = dimnames(coordinates(sdf))[[2]]
321 formula = as.formula(paste(ccn[2], "~", ccn[1]))
322 }
323 }
324 scales = longlat.scales(obj, scales, xlim, ylim)
325 args.xyplot = append(list(formula, data = as(sdf, "data.frame"),
326 panel = panel, aspect = aspect, scales = scales,
327 xlab = xlab, ylab = ylab, sp.layout = sp.layout,
328 xlim = xlim, ylim = ylim, edge.col = edge.col,
329 col.regions = col.regions), dots)
330 z = create.z(as(obj, "data.frame"), zcol)
331 args.xyplot = fill.call.groups(args.xyplot, z = z, edge.col = edge.col,
332 colorkey = colorkey, ...)
333 # debug:
334 #print(args.xyplot)
335 plt = do.call(xyplot, args.xyplot)
336 if (!(is.logical(identify) && identify==FALSE) && interactive()) {
337 print(plt)
338 if (!(is.numeric(identify) && length(identify) == 2))
339 identify = c(1,1)
340 trellis.focus("panel", identify[1], identify[2])
341 labels = row.names(as(sdf, "data.frame"))
342 cat("left-mouse to identify points; right-mouse to end\n")
343 cc = coordinates(obj)
344 ret = panel.identify(cc[,1], cc[,2], labels)
345 trellis.unfocus()
346 return(ret)
347 } else
348 plt
349 }
350 setMethod("spplot", signature("SpatialPointsDataFrame"), spplot.points)
351
352 setMethod("spplot", signature("SpatialMultiPointsDataFrame"),
353 function(obj, ...) spplot.points(as(obj, "SpatialPointsDataFrame"), ...))
354
355 create.z = function(df, zcol) {
356 if (is.logical(df[[zcol[1]]])) {
357 z = stack(df[zcol])[[1]]
358 z = as.factor(z)
359 } else if (is.numeric(df[[zcol[1]]]))
360 z = stack(df[zcol])[[1]]
361 else if (is.factor(df[[zcol[1]]])) {
362 lev = levels(df[[zcol[1]]])
363 z = factor(as.vector(sapply(df[zcol], as.character)), levels = lev)
364 } else
365 stop("no support for variable of this type")
366 z
367 }
368
369 panel.gridplot = function(x, y, z, subscripts, ..., sp.layout) {
370 sppanel(list(sp.layout), panel.number(), first = TRUE)
371 panel.levelplot(x, y, z, subscripts, ...)
372 sppanel(list(sp.layout), panel.number(), first = FALSE)
373 }
374
375 panel.polygonsplot =
376 function (x, y, z, subscripts, at = pretty(z), shrink, labels = NULL,
377 label.style = c("mixed", "flat", "align"), contour = FALSE,
378 region = TRUE, col = add.line$col, lty = add.line$lty,
379 lwd = add.line$lwd,
380 cex = add.text$cex, font = add.text$font,
381 fontfamily = add.text$fontfamily,
382 fontface = add.text$fontface, col.text = add.text$col, ...,
383 col.regions = regions$col, alpha.regions = regions$alpha,
384 grid.polygons, sp.layout)
385 {
386 regions <- trellis.par.get("regions")
387 add.line <- trellis.par.get("add.line")
388 add.text <- trellis.par.get("add.text")
389 numcol <- length(at) - 1
390 numcol.r <- length(col.regions)
391 col.regions <- if (numcol.r <= numcol)
392 rep_len(col.regions, numcol)
393 else col.regions[floor(1 + (1:numcol - 1) * (numcol.r - 1)/(numcol - 1))]
394 zcol <- rep(NA, length(z))
395 for (i in seq_along(col.regions)) zcol[!is.na(x) & !is.na(y) &
396 !is.na(z) & z >= at[i] & z < at[i + 1]] <- i
397 label.style <- match.arg(label.style)
398 x <- as.numeric(x[subscripts])
399 y <- as.numeric(y[subscripts])
400 z <- as.numeric(z[subscripts])
401 zcol <- as.numeric(zcol[subscripts])
402
403 sppanel(list(sp.layout), panel.number(), first = TRUE)
404 if (any(subscripts)) {
405 if (is(grid.polygons, "SpatialLines")) {
406 sp.lines3 = function(x, col, ...) panel.lines(coordinates(x), col = col, ...)
407 sp.lines2 = function(x, col, ...) lapply(x@Lines, sp.lines3, col, ...)
408 for (i in 1:length(grid.polygons@lines))
409 sp.lines2(grid.polygons@lines[[i]], col = col.regions[zcol[i]], lwd = lwd, lty = lty, ...)
410 } else {
411 pls = slot(grid.polygons, "polygons")
412 pO = slot(grid.polygons, "plotOrder")
413 col = rep(col, length.out = length(grid.polygons))
414 for (i in pO) {
415 if (get_Polypath()) {
416 obj = as(as(grid.polygons[i,], "SpatialLines"),
417 "SpatialPointsDataFrame")
418 cc = coordinates(obj)
419 id = as.numeric(obj$Line.NR)
420 fill = col.regions[zcol[i]]
421 alpha = alpha.regions
422 grid.path(cc[,1], cc[,2], id, default.units = "native",
423 gp = gpar(col = col[i], fill = fill, alpha = alpha,
424 lwd = lwd, lty = lty, ...))
425 } else {
426 Srs <- slot(pls[[i]], "Polygons")
427 pOi <- slot(pls[[i]], "plotOrder")
428 for (j in pOi) {
429 coords = slot(Srs[[j]], "coords")
430 if (slot(Srs[[j]], "hole")) {
431 bg = trellis.par.get()$background
432 if (bg$col == "transparent")
433 fill = "white"
434 else
435 fill = bg$col
436 alpha = bg$alpha
437 } else {
438 fill = col.regions[zcol[i]]
439 alpha = alpha.regions
440 }
441 gp = gpar(fill = fill, alpha = alpha, col = col, lwd = lwd, lty = lty)
442 grid.polygon(coords[,1], coords[,2], default.units = "native",
443 gp = gp)
444 }
445 }
446 }
447 }
448 }
449 sppanel(list(sp.layout), panel.number(), first = FALSE)
450 }
451
452 panel.pointsplot = function(sp.layout, x, y, subscripts, groups, col, cex,
453 pch, ...) {
454 sppanel(list(sp.layout), panel.number(), first = TRUE)
455 lpoints(x, y, fill = groups[subscripts], col = col[subscripts],
456 cex = cex[subscripts], pch = pch[subscripts], ...)
457 sppanel(list(sp.layout), panel.number(), first = FALSE)
458 }
459
460 SpatialPolygons2Grob = function(obj, fill) {
461 if (!is(obj, "SpatialPolygons"))
462 stop("object is not of class SpatialPolygons")
463 x = numeric(0)
464 y = numeric(0)
465 id = integer(0)
466 pls = slot(obj, "polygons")
467 pO <- slot(obj, "plotOrder")
468 n = 0
469 for (i in pO) {
470 Srs <- slot(pls[[i]], "Polygons")
471 pOi <- slot(pls[[i]], "plotOrder")
472 for (j in pOi) {
473 n = n + 1
474 cc = slot(Srs[[j]], "coords")
475 x = c(x, cc[,1])
476 y = c(y, cc[,2])
477 id = c(id, rep(n, nrow(cc)))
478 }
479 }
480 polygonGrob(x=x, y=y, id=id, gp = gpar(fill = fill))
481 }
482
483 SpatialPolygonsRescale = function(obj, offset, scale = 1, fill = "black", col = "black", plot.grid = TRUE, ...) {
484 if (!is(obj, "SpatialPolygons"))
485 stop("object is not of class SpatialPolygons")
486 if (length(offset) != 2)
487 stop("offset should have length 2")
488 if (is.list(offset))
489 offset = c(offset[[1]], offset[[2]])
490 if (length(scale) == 1)
491 scale = rep(scale,2)
492 pls = slot(obj, "polygons")
493 pO = slot(obj, "plotOrder")
494 fill = rep_len(fill, length(pls))
495 for (i in pO) {
496 Srs <- slot(pls[[i]], "Polygons")
497 pOi <- slot(pls[[i]], "plotOrder")
498 for (j in pOi) {
499 cc = slot(Srs[[j]], "coords")
500 x = offset[1] + (cc[,1] * scale[1])
501 y = offset[2] + (cc[,2] * scale[2])
502 if (plot.grid) {
503 grid.polygon(x, y, default.units = "native",
504 gp = gpar(col = col, fill = fill[i], ...))
505 } else {
506 polygon(x, y, col = fill[i])
507 lines(x, y, col = col)
508 }
509 }
510 }
511 }
512
513 mapLegendGrob <- function(obj, widths = unit(1, "cm"), heights = unit(1, "cm"),
514 fill = "black", just = "right") {
515 grb = SpatialPolygons2Grob(obj, fill)
516 key.layout <- grid.layout(nrow = 1, ncol = 1, widths = widths,
517 heights = heights, respect = TRUE, just = just)
518 key.gf <- frameGrob(layout = key.layout)
519 key.gf <- placeGrob(key.gf,
520 rectGrob(gp = gpar(fill = "transparent", col = NULL)),
521 row = NULL, col = NULL)
522 key.gf <- placeGrob(key.gf, grb, row = 1, col = 1)
523 key.gf
524 }
525
526 layout.north.arrow = function(type = 1) {
527 if (type == 1) {
528 x1 = c(0.1653, 0.2241, 0.2241, 0.2830, 0.1947, 0.1065, 0.1653, 0.1653)
529 x2 = c(0, 0.0967, 0.0967, 0.2928, 0.3908, 0.3908, 0.2928, 0.2928, 0.1032, 0, 0)
530 y1 = c(0, 0, 0.8823, 0.8235, 1, 0.8235, 0.8823, 0)
531 y2 = c(0.2352, 0.2352, 0.5686, 0.2352, 0.2352, 0.7189, 0.7189, 0.3986, 0.7189, 0.7189, 0.2352 )
532 return(SpatialPolygons(list(Polygons(list(Polygon(cbind(x1,y1)), Polygon(cbind(rev(x2),rev(y2)))), ID="north"))))
533 }
534 if (type == 2) {
535 x = c(0.143,0.143,0.0143,0.207,0.400,0.271,0.271,0.143)
536 y = c(0,0.707,0.707,0.964,0.707,0.707,0.00,0.0)
537 return(SpatialPolygons(list(Polygons(list(Polygon(cbind(x,y))), ID="north"))))
538 }
539 stop("unknown value for type")
540 }
541
542 layout.scale.bar = function(height = 0.05) {
543 x1 = c(0, 0.5, 0.5, 0, 0)
544 y1 = c(0, 0, height, height, 0)
545 x2 = x1 + 0.5
546 y2 = y1
547 SpatialPolygons(list(Polygons(list(Polygon(cbind(x1,y1))), ID="left"),
548 Polygons(list(Polygon(cbind(rev(x2),rev(y2)))), ID="right")))
549 }
550 # scale.bar = .scale.bar()
551
552 sp.theme = function(set = FALSE, regions = list(col = bpy.colors(100)), ...) {
553 lst = list(regions = regions, ...)
554 if (set)
555 trellis.par.set(lst)
556 else
557 lst
558 }
559
560 spplot.key = function(sp.layout, rows = 1, cols = 1) {
561 for (i in seq_along(rows)) {
562 for (j in seq_along(cols)) {
563 trellis.focus("panel", cols[j], rows[i], highlight = FALSE)
564 sppanel(sp.layout)
565 trellis.unfocus()
566 }
567 }
568 }
569
570 #sp.pagefn = function(n) {
571 # pos = lattice:::lattice.getStatus("current.panel.positions")
572 # spplot.key(sp.layout, pos[1], pos[2])
573 #}
574
575 longlat.scales = function(obj, scales, xlim, ylim) {
576 if (!is.null(scales$draw) && scales$draw &&
577 !is.na(isp <- is.projected(obj)) && !isp) {
578 # long lat -- x:
579 if (is.null(scales$x))
580 scales$x = list()
581 if (is.null(scales$x$at))
582 scales$x$at = pretty(xlim)
583 if (is.null(scales$x$labels))
584 scales$x$labels = parse(text = degreeLabelsEW(scales$x$at))
585 # long lat -- y:
586 if (is.null(scales$y))
587 scales$y = list()
588 if (is.null(scales$y$at))
589 scales$y$at = pretty(ylim)
590 if (is.null(scales$y$labels))
591 scales$y$labels = parse(text = degreeLabelsNS(scales$y$at))
592 }
593 scales
594 }
595
596 bbexpand = function(x, fraction) {
597 r = diff(x)
598 c(x[1] - fraction * r, x[2] + fraction * r)
599 }
600
601 colorkey.factor = function(f, colorkey = list(), doColorkey = TRUE) {
602 lf = levels(f)
603 at = seq(0.5, nlevels(f)+0.501)
604 at.labels = seq(1, nlevels(f))
605 if (doColorkey) {
606 colorkey=append(colorkey, list(labels=list(at=at.labels, labels=lf),
607 height=min(1, .05 * length(lf))))
608 list(at = at, colorkey = colorkey)
609 } else
610 list(at = at)
611 }
612
613 "spplot.locator" <- function(n = 512, type = "n", ...) {
614 stopifnot(n > 0)
615 res = as.numeric(grid.locator(unit = "native"))
616 if (type == "o" || type == "p")
617 panel.points(res[1], res[2], ...)
618 if (n > 1) for (i in 2:n) {
619 xy = grid.locator(unit = "native")
620 if (is.null(xy))
621 # return(res)
622 break
623 else
624 xy = as.numeric(xy)
625 res = rbind(res, xy)
626 if (type == "o" || type == "p")
627 panel.points(xy[1], xy[2], ...)
628 if (type == "o" || type == "l")
629 panel.lines(res[(i-1):i,])
630 }
631 if (is.matrix(res))
632 dimnames(res) = list(NULL, NULL)
633 res
634 }
635
636 addNAemptyRowsCols = function(obj) {
637 # accept gridded; return SpatialPointsDataFrame with NA records on empty row/cols
638 fullgrid(obj) = FALSE
639 nfull = obj@[email protected][1] * obj@[email protected][2]
640 missingpatt = rep(TRUE, nfull)
641 missingpatt[[email protected]] = FALSE
642 missingpatt = matrix(missingpatt,
643 obj@[email protected][1], obj@[email protected][2], byrow = FALSE)
644 missing.x = which(apply(missingpatt, 1, all))
645 missing.y = which(apply(missingpatt, 2, all))
646
647 xy = coordinates(obj)[,1:2,drop=FALSE]
648 coordvals = coordinatevalues(obj@grid)
649 missing.x = coordvals[[1]][missing.x]
650 missing.y = coordvals[[2]][missing.y]
651 n = length(missing.x) + length(missing.y)
652 if (n > 0) {
653 if (length(missing.x) > 0)
654 xy = rbind(xy, cbind(missing.x, rep(xy[1,2], length(missing.x))))
655 if (length(missing.y) > 0)
656 xy = rbind(xy, cbind(rep(xy[1,1], length(missing.y)), missing.y))
657 newatt = data.frame(lapply(obj@data, function(x) c(x, rep(NA, n))))
658 row.names(xy) = seq_len(nrow(xy))
659 obj = SpatialPointsDataFrame(xy, newatt, [email protected], obj@proj4string, FALSE)
660 } else
661 obj = as(obj, "SpatialPointsDataFrame")
662 obj
663 }
664
665 fill.call.groups <-
666 function (lst, z, ..., cuts = ifelse(identical(FALSE, colorkey), 5, 100),
667 #col.regions = trellis.par.get("regions")$col,
668 legendEntries = "", pch, cex = 1, do.fill = TRUE, do.log = FALSE,
669 key.space = ifelse(identical(FALSE, colorkey), "bottom", "right"),
670 cex.key, edge.col, colorkey)
671 {
672 dots = list(...)
673 col.regions = lst$col.regions
674 if (is.numeric(z)) {
675 if (length(cuts) > 1)
676 ncuts = length(cuts) - 1
677 else ncuts = cuts
678 if (ncuts != length(col.regions)) {
679 cols = round(1 + (length(col.regions) - 1) * (0:(ncuts -
680 1))/(ncuts - 1))
681 fill = col.regions[cols]
682 } else
683 fill = col.regions
684 valid = !is.na(z)
685 if (length(cuts) == 1) {
686 if (do.log) {
687 lz = log(z)
688 cuts = c(min(z[valid]), exp(seq(min(lz[valid]),
689 max(lz[valid]), length = cuts + 1))[2:(cuts)],
690 max(z[valid]))
691 }
692 else cuts = seq(min(z[valid]), max(z[valid]), length.out = cuts +
693 1)
694 }
695 groups = cut(as.matrix(z), cuts, dig.lab = 4, include.lowest = TRUE)
696 } else if (is.factor(z)) {
697 if (length(col.regions) == 1)
698 col.regions = rep(col.regions, nlevels(z))
699 if (length(col.regions) < nlevels(z))
700 stop("number of colors smaller than number of factor levels")
701 if (length(col.regions) > nlevels(z)) {
702 ncuts = nlevels(z)
703 cols = round(1 + (length(col.regions) - 1) * (0:(ncuts -
704 1))/(ncuts - 1))
705 col.regions = col.regions[cols]
706 }
707 if (!missing(cuts))
708 stop("ncuts cannot be set for factor variable")
709 groups = z
710 fill = col.regions
711 } else stop("dependent of not-supported class")
712 n = nlevels(groups)
713
714 # deal with col:
715 lst$groups = fill[groups]
716 #print(lst$col)
717
718 # deal with pch:
719 if (edge.col != "transparent") { # WITH border: use fill
720 if (missing(pch))
721 pch = rep(ifelse(do.fill, 21, 1), n)
722 lst$col = rep(edge.col, length.out = length(groups))
723 } else { # no border: use col instead of fill
724 if (missing(pch))
725 pch = rep(ifelse(do.fill, 16, 1), n)
726 lst$col = lst$groups
727 }
728
729 if (length(pch) == 1)
730 pch = rep(pch, n)
731 lst$pch = pch[groups]
732
733 # deal with cex:
734 if (missing(cex))
735 cex = rep(1, n)
736 if (length(cex) == 1)
737 cex = rep(cex, n)
738 if (length(cex) == n) {
739 cex.key = cex
740 lst$cex = cex[groups]
741 lst$cex[is.na(lst$cex)] = 0
742 } else if (missing(cex.key))
743 cex.key = mean(cex, na.rm = TRUE)
744
745 # do key:
746 if (is.list(colorkey))
747 lst$legend = colorkey
748 else if (isTRUE(colorkey)) {
749 lst$legend = list(
750 right = list(
751 fun = draw.colorkey,
752 args = list(
753 key = list(
754 col = col.regions,
755 at = cuts
756 ),
757 draw = FALSE
758 )
759 )
760 )
761 if (is.character(key.space))
762 names(lst$legend) = key.space
763 } else {
764 if (!identical(dots$auto.key, FALSE)) { # xxx
765 if (missing(legendEntries))
766 legendEntries = levels(groups)
767 if (!is.null(dots$key))
768 lst$key = dots$key
769 else {
770 if(is.list(dots$auto.key))
771 lst$key = dots$auto.key
772 else
773 lst$key = list()
774 if (edge.col != "transparent") {
775 lst$key = append(lst$key,
776 list(points = list(
777 pch = rep(pch, length.out = n),
778 col = rep(edge.col, length.out = n),
779 fill = fill,
780 cex = rep(cex.key, length.out = n)
781 ),
782 text = list(legendEntries)
783 ))
784 } else {
785 lst$key = append(lst$key,
786 list(points = list(
787 pch = rep(pch, length.out = n),
788 col = rep(fill, length.out = n),
789 cex = rep(cex.key, length.out = n)
790 ),
791 text = list(legendEntries)
792 ))
793 }
794 }
795 if (is.character(key.space))
796 lst$key$space = key.space
797 else if (is.list(key.space))
798 lst$key = append(lst$key, key.space)
799 else warning("key.space argument ignored (not list or character)")
800 # print(lst$key)
801 }
802 if (!is.null(dots$auto.key))
803 lst$auto.key <- dots$auto.key
804 }
805 return(lst)
806 }
807
808 panel.RgoogleMaps <- function(map) {
809 bb = bb2merc(map, "RgoogleMaps")
810 grid.raster(map$myTile, mean(bb[1,]), mean(bb[2,]), diff(bb[1,]), diff(bb[2,]),
811 default.units = "native", interpolate = FALSE)
812 }
813
814 panel.ggmap <- function(map) {
815 bb = bb2merc(map, "ggmap")
816 grid.raster(map, mean(bb[1,]), mean(bb[2,]), diff(bb[1,]), diff(bb[2,]),
817 default.units = "native", interpolate = FALSE)
818 }