Debian Codegraph @

R/gridlines.R

raw
1 degreeLabelsNS = function(x) {
2 pos = sign(x) + 2
3 dir = c("*S", "", "*N")
4 paste0(abs(x), "*degree", dir[pos])
5 }
6 degreeLabelsEW = function(x) {
7 x <- ifelse(x > 180, x - 360, x)
8 pos = sign(x) + 2
9 if (any(x == -180))
10 pos[x == -180] = 2
11 if (any(x == 180))
12 pos[x == 180] = 2
13 dir = c("*W", "", "*E")
14 paste0(abs(x), "*degree", dir[pos])
15 }
16
17 gridlines = function(x, easts = pretty(bbox(x)[1,]),
18 norths = pretty(bbox(x)[2,]), ndiscr = 100)
19 {
20 if (missing(x)) {
21 if (missing(easts) && missing(norths)) {
22 easts = seq(-180, 180, 20)
23 norths = seq(-80, 80, 20)
24 bb = matrix(c(-180, 180, -90, 90), 2, 2, byrow = TRUE)
25 }
26 crs = CRS("+init=epsg:4326")
27 } else {
28 bb = bbox(x)
29 crs = slot(x, "proj4string")
30 easts <- easts[easts >= bb[1,1] & easts <= bb[1,2]]
31 norths <- norths[norths >= bb[2,1] & norths <= bb[2,2]]
32 }
33 #easts <- easts[easts > bb[1,1] & easts < bb[1,2]]
34 eastlist <- vector(mode="list", length=length(easts))
35 for (i in 1:length(easts))
36 eastlist[[i]] <- Line(cbind(rep(easts[i], ndiscr),
37 seq(bb[2,1], bb[2,2], length.out=ndiscr)))
38 #norths <- norths[norths > bb[2,1] & norths < bb[2,2]]
39 northlist <- vector(mode="list", length=length(norths))
40 for (i in 1:length(norths))
41 northlist[[i]] <- Line(cbind(seq(bb[1,1], bb[1,2], length.out=ndiscr),
42 rep(norths[i], ndiscr)))
43 SpatialLines(list(Lines(northlist, "EW"), Lines(eastlist, "NS")), crs)
44 }
45
46 gridat <- function(x, easts = pretty(bbox(x)[1,]),
47 norths = pretty(bbox(x)[2,]), offset=0.5, side="WS")
48 {
49 isp = is.projected(x)
50 if (is.na(isp) || isp) stop("x must not be projected")
51 bb = bbox(x)
52 ac <- ifelse (side == "WS", 1L, 2L)
53 easts <- easts[easts > bb[1,1] & easts < bb[1,2]]
54 norths <- norths[norths > bb[2,1] & norths < bb[2,2]]
55 a1 <- cbind(easts, rep(bb[2,ac], length(easts)))
56 a1lab <- degreeLabelsEW(a1[,1])
57 a2 <- cbind(rep(bb[1,ac], length(norths)), norths)
58 a2lab <- degreeLabelsNS(a2[,2])
59 as <- SpatialPoints(rbind(a1, a2), slot(x, "proj4string"))
60 res <- SpatialPointsDataFrame(as,
61 data.frame(labels = c(a1lab, a2lab),
62 pos = c(rep(1L+((ac-1)*2), length(easts)),
63 rep(2L+((ac-1)*2), length(norths))),
64 offset = rep(offset, length(easts)+length(norths)),
65 stringsAsFactors = FALSE
66 )
67 )
68 res
69 }