# [R] Covered Labels

Jim Lemon bitwrit at ozemail.com.au
Thu Jun 24 06:05:09 CEST 2004

```Martina Renninger wrote:
> Dear All!
>
>
>
> How can I cope with overlapping or covered labels (covered by labels
> from other data points) in plots?

This doesn't solve every such problem, but it has helped me in the past.
You will probably have to expand the xlim and ylim a bit to fit the extreme
labels onto the plot.

Also, there seems to be a typo in the HTML help for dist(), mentioning
as.matrix.dist() which should be as.matrix().

Jim
-------------- next part --------------
# thigmophobe returns the direction (as n|e|s|w) _away_ from
# the nearest point where x and y are vectors of 2D coordinates

thigmophobe<-function(x,y) {
# get the current upper and lower limits of the plot
plot.span<-par("usr")
x.span<-plot.span[2] - plot.span[1]
y.span<-plot.span[4] - plot.span[3]
# if either axis is logarithmic, transform the values into logarithms
if(par("xlog")) x<-log(x)
if(par("ylog")) y<-log(y)
# scale the values to the plot span
# this avoids the numerically larger
# axis dominating the distance measure
x<-x/x.span
y<-y/y.span
# get the distance matrix as a full matrix
xy.dist<-as.matrix(dist(cbind(x,y)))
lenx<-length(x)
nearest.index<-rep(0,lenx)
for(index in 1:lenx)
nearest.index[index]<-as.numeric(names(which.min(xy.dist[-index,index])))
# get the x and y differences for each point to the nearest point
xdiff<-x - x[nearest.index]
ydiff<-y - y[nearest.index]
# first set the east/west direction
dir.ew<-ifelse(xdiff > 0,"e","w")
# now do the north/south
dir.ns<-ifelse(ydiff > 0,"n","s")
dir.away<-ifelse(abs(xdiff)>abs(ydiff),dir.ew,dir.ns)
return(dir.away)
}

# thigmophobe.labels positions labels at points so that they
# are most distant from the nearest other point, where the
# points are described as x and y coordinates.

thigmophobe.labels<-function(x,y,labels,...) {
if(!missing(x) && !missing(y)) {
lenx<-length(x)
if(missing(labels)) labels<-as.character(1:lenx)
dir.away<-thigmophobe(x,y)
for(i in 1:lenx) {
if(dir.away[i] == "n") {
}
if(dir.away[i] == "e") {
}
if(dir.away[i] == "s") {
}
if(dir.away[i] == "w") {