File: lineLabel.R

package info (click to toggle)
r-cran-maptools 1%3A1.1-6%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 2,984 kB
  • sloc: ansic: 3,025; makefile: 5; sh: 4
file content (288 lines) | stat: -rw-r--r-- 11,305 bytes parent folder | download
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
# Author: Oscar Perpinan Lamigueiro oscar.perpinan@gmail.com
# Date :  October 2012
# Version 0.10
# Licence GPL v3

lineLabel <- function(line, label,
                      spar=.6, position = c('above', 'below'),
                      textloc = 'constantSlope',
                      col = add.text$col,
                      alpha = add.text$alpha,
                      cex = add.text$cex,
                      lineheight = add.text$lineheight,
                      font = add.text$font,
                      fontfamily = add.text$fontfamily,
                      fontface = add.text$fontface,
                      lty = add.line$lty,
                      lwd = add.line$lwd, 
                      col.line = add.line$col,
                      identifier = 'lineLabel',
                     ...){
  .Deprecated("", package="maptools", old="lineLabel",
    msg="Function moved to https://github.com/oscarperpinan/label")
  ## line is a list of Line objects
  ## label and line must be of equal length
  stopifnot(is.numeric(textloc) | is.character(textloc))
  stopifnot(length(line) == length(label))
  if (is.numeric(textloc)) stopifnot(length(line) == length(textloc))

  add.text <- trellis.par.get("add.text")
  add.line <- trellis.par.get("add.line")

  position <- match.arg(position)

  for (i in seq_along(line)) {
    subline <- line[[i]]
    lbl <- label[i]
    
    coords <- xy.coords(coordinates(subline))

    llines(coords,
           col = col.line, lty=lty, lwd=lwd,
           identifier = paste(identifier, "line", ## add ID?
             sep = "."))

    if (lbl !='') { ## Only execute if label is not empty
      ## Where the label is to be placed?
      ## Method "mixed" from lattice::panel.levelplot
      coords <- with(coords, data.frame(x, y))
      slopes <- diff(coords$y) / diff(coords$x)
      slopes[is.infinite(slopes)] <- NA
 
      rx <- range(coords$x)
      ry <- range(coords$y)

      stopifnot(is.character(textloc) | is.numeric(textloc))
      
      if (is.character(textloc)){
        textloc <- match.arg(textloc, c('minSlope', 'maxDepth', 'constantSlope'))

        idxLoc <- switch(textloc,
                          minSlope = which.min(abs(slopes)),
                          maxDepth = {
                            depth <- pmin(pmin(coords$x - rx[1], rx[2] - coords$x) / diff(rx), 
                                          pmin(coords$y - ry[1], ry[2] - coords$y) / diff(ry))
                            min(which.max(depth), length(slopes))
                            },
                          constantSlope = {
                            slopeSign <- sign(slopes)
                            zeros <- which(slopes==0)
                            for (i in zeros) {
                              i1 <- max(1, i-1)
                              i2 <- min(length(slopes), i + 1)
                              slopeSign[i] <- sign(sum(slopes[c(i1, i2)], na.rm=1))
                              }
                            rleSlopes <- rle(slopeSign)
                            idxCS <- max(which.max(rleSlopes$lengths) - 1, 1)
                            cumLengths <- cumsum(rleSlopes$lengths)
                            idxLim <- c(cumLengths[idxCS] +1, cumLengths[idxCS + 1])
                            idxLim[1]
                            ## idx1 <- cumsum(rleSlopes$lengths)[idxCS] + 1
                            ## idx2 <- idx1 + rleSlopes$lengths[idxCS + 1] - 1
                            ## which(coords[,1] == min(coords[c(idx1, idx2), 1]))
                            }
                          )
        } else {idxLoc <- textloc[i]}
      
      ## Label: number of characters, width and height
      gp <- gpar(col = col,
                 alpha = alpha,
                 cex = cex,
                 lineheight = lineheight,
                 fontfamily = fontfamily,
                 fontface = fontface)
      chars <- strsplit(lbl, '')[[1]]
      nchars <- length(chars)


      chWidth <- sapply(chars, function(ch){
        chGrob <- textGrob(ch, gp=gp)
        gWidth <- grobWidth(chGrob)
        convertWidth(gWidth, 'native', valueOnly=TRUE)
      })

      labLength <- sum(chWidth)

      chHeight <- sapply(chars, function(ch){
        chGrob <- textGrob(ch, gp=gp)
        gHeight <- grobHeight(chGrob)
        convertHeight(gHeight, 'native', valueOnly=TRUE)
      })
      labHeight <- max(chHeight)

      ##------------------------------------------------------------------##
      ## Starting at idxLoc, extract the segment of the line to be
      ## followed. It must be long enough for the text
      ##------------------------------------------------------------------##

      lengths <- LineLength(subline, sum=FALSE, longlat=FALSE)
      nParts <- length(lengths)
      lengthsLoc <- cumsum(lengths[idxLoc:nParts])

      if (labLength > lengthsLoc[nParts - idxLoc +1]) { ##The segment is not long enough for the label
        idxLoc <- 1
        segCoords <- apply(coords, 2, mean)
        slopes <- mean(slopes, na.rm=TRUE)
      } else {
        idxLength <- min(which(lengthsLoc >= labLength))
        segCoords <- coords[idxLoc:(idxLoc+idxLength),]
        segment <- Line(segCoords)
        lengthSeg <- LineLength(segment)
      }

      nX <- nrow(segCoords)
      if (!is.null(nX) && nX >= 4) { ## smooth.spline needs at least four distinct x values

        ##------------------------------------------------------------------##
        ## Resample the segment to obtain a collection of short segments.
        ##------------------------------------------------------------------##

        n <- floor(lengthSeg/min(chWidth)) * 1e3

        segSplineFun <- smooth.spline(segCoords, spar = spar) ## change spar to adjust the smooth level
        rxSeg <- range(segCoords$x)
        xsp <- seq(rxSeg[1], rxSeg[2], length=n) ## new x values to resample the segment
        segSpline <- data.frame(predict(segSplineFun, xsp))

        ## Each letter will be placed above a midpoint of this resampled segment
        midPoints <- 1/2 * (segSpline[1:(n-1), ] + segSpline[2:n, ])
        slopes <- diff(segSpline$y) / diff(segSpline$x)

        ##------------------------------------------------------------------##
        ## Parallel translation of the resampled segment. The distant is fixed
        ## by the height of the label.
        ##------------------------------------------------------------------##

        ## Distance between segments
        D <- labHeight
        ## Unitary perpendicular vector
        perp <- data.frame(x=-diff(segSpline$y), y=diff(segSpline$x))
        len <- apply(perp, 1, FUN=function(v)sqrt(sum(v^2)))
        perp <- perp/len

        ## Points above (+) or below (-) line

        if (position =='below') D <- abs(D) else D <- -abs(D)
        segOffset <- sweep(midPoints, 2, D * colMeans(perp))
        ##segOffset <- midPoints +  D*perp

        segSplineLine <- Line(segOffset) ##Line(segSpline)
        lengthSegSpline <- LineLength(segSplineLine, sum=FALSE)

        ## sp.lines(segSplineLine, col='blue')

        ##------------------------------------------------------------------##
        ## A character is placed above a collection of segments whose total
        ## length is higher than the character width. IDs is a vector of
        ## indices to subset the parallel segment.
        ##------------------------------------------------------------------##

        id <- IDs <- 1
        lengths <- lengthSegSpline
        nSegs <- length(lengths)
        for (i in 2:nchars){
          D <- cumsum(lengths)
          L <- 1/2*(chWidth[i-1] + chWidth[i])
          id <- min(which(D>=L))
          lengths <- lengths[(id+1):nSegs]
          IDs <- c(IDs, id)
        }
        IDs <- cumsum(IDs)

        pts <- SpatialPoints(segOffset)[IDs,] 
        coordLabs <- coordinates(pts)
        slopeLabs <- 180/pi * atan(slopes[IDs])

        tg <- textGrob(chars, coordLabs[,1], coordLabs[,2],
                       default.units='native',
                       rot=slopeLabs,
                       gp=gp)
        grid.draw(tg)

      } else { ## without 4 distinct x values
        coordLabs <- coords[idxLoc,]
        slopeLabs <- 180/pi * atan(slopes[idxLoc])
        just <- if (position=='below') 'top' else 'bottom'

        tg <- textGrob(lbl, coordLabs[,1], coordLabs[,2],
                       just=just,
                       default.units='native',
                       rot=slopeLabs,
                       gp=gp)
        grid.draw(tg)



      }
      ## lapply(1:nchars, FUN=function(i){
      ##   pg <- circleGrob(coordLabs[i,1], coordLabs[i,2], r=chWidth[i]/2,
      ##                    default.units='native', gp=gpar(col='red'))
      ##   grid.draw(pg)
      ##  })
    }}
}

setGeneric('sp.lineLabel', function(object, labels, byid=TRUE,...){standardGeneric('sp.lineLabel')})

setMethod('sp.lineLabel',
          signature=(object='Lines'),
          definition=function(object, labels, byid=TRUE, ...){
  .Deprecated("", package="maptools", old="sp.lineLabel",
    msg="Function moved to https://github.com/oscarperpinan/label")
            if (missing(labels)) labels=object@ID
            if (isTRUE(byid)){
              lengths <- sapply(object@Lines, LineLength)
              idxMax <- which.max(lengths)
              labs <- rep('', length(object@Lines))
              labs[idxMax] <- labels
            } else {
              labs <- rep(labels, length(object@Lines))
            }
            lineLabel(object@Lines, label=labs, ...)
          }
          )

setMethod('sp.lineLabel',
          signature=(object='SpatialLines'),
          definition=function(object, labels, byid=TRUE,...){
  .Deprecated("", package="maptools", old="sp.lineLabel",
    msg="Function moved to https://github.com/oscarperpinan/label")
            if (missing(labels)) labels=object@ID
            if (isTRUE(byid)){
              lengths <- sapply(object@Lines, LineLength)
              idxMax <- which.max(lengths)
              labs <- rep('', length(object@Lines))
              labs[idxMax] <- labels
            } else {
              labs <- rep(labels, length(object@Lines))
            }
            if (missing(labels)){
              ids <- sapply(object@lines, function(l)l@ID)
              labels <- ids
              names(labels) <- ids
            }
            for (i in seq_along(object)){
              line <- object@lines[[i]]
              idLabel <- match(line@ID, names(labels))
              lbl <- if (is.na(idLabel)) '' else as.graphicsAnnot(labels[idLabel])
              sp.lineLabel(line, lbl, byid=byid,...)
            }
          }
          )


setGeneric('label', function(object, text,...){standardGeneric('label')})

setMethod('label', signature=(object='SpatialLines'),
          definition=function(object, text,...){
  .Deprecated("", package="maptools", old="label",
    msg="Function moved to https://github.com/oscarperpinan/label")
            text <- as.character(text)
            nfeatures <- length(object)
            if (!identical(nfeatures, length(text))){
              stop('Number of labels must equal number of features.')
            }
            ids <- sapply(object@lines, function(l)l@ID)
            names(text) <- ids
            text
          })