File: thigmophobe.R

package info (click to toggle)
r-cran-plotrix 3.8-4-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,588 kB
  • sloc: makefile: 6
file content (31 lines) | stat: -rwxr-xr-x 1,273 bytes parent folder | download | duplicates (3)
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
# function contributed by Bill Venables as a replacement for thigmophobe
thigmophobe <- function (x, y = NULL, names = seq_along(z),
                   xlog = par("xlog"), ylog = par("ylog"), 
                   usr = par("usr"), pin = par("pin"), 
                   eps = .Machine$double.eps, pi = base::pi) {
  # convert separete x and y coordinates to a two element list
  xy <- grDevices::xy.coords(x, y, recycle = TRUE)
  z <- with(xy, {
    x <- ((if(xlog) log(x) else x) - usr[1])/diff(usr[1:2])*pin[1]
    y <- ((if(ylog) log(y) else y) - usr[3])/diff(usr[3:4])*pin[2]
    complex(real = x, imaginary = y)
  })
  # calculate the matrix of distances
  xydist <- outer(z, z, function(x, y) Mod(x - y))
  # remove "self" distances
  diag(xydist) <- Inf
  # get the indicies of the smallest distances
  nearby <- apply(xydist, 2, which.min)
  zdiff <- z - z[nearby]
  # get the offset away from the nearest point for each label
  pos <- findInterval((-pi/4 - Arg(zdiff)) %% (2*pi), 
                      seq(0, 2*pi, by = pi/2), all.inside = TRUE)
  # stagger the offsets for points with essentially zero differences
  if(any(k <- Mod(zdiff) <= eps)) {
    for(k in which(k)) {
      pos[sort(c(k, nearby[k]))] <- c(1,3)
    }
  }
  names(pos)<-names
  return(pos)
}