14

I would like to jitter the text on a plot so as to avoid overplotting. To do so, I assume that I need a bounding box around the text component. Is there a way to get this?

For example, in base graphics:

plot.new()
text(.5,.5,"word")
text(.6,.5,"word") #does this overlap?

In grid there is a way to drop overlapping text, but I can't seem to find a way to access the code that figures out if overlapping has occurred.

grid.text(c("word","other word"),c(.5,.6),c(.5,.5),check=T)
Ian Fellows
  • 17,228
  • 10
  • 49
  • 63

3 Answers3

6

Maybe the strwidth and strheight functions can help here

stroverlap <- function(x1,y1,s1, x2,y2,s2) {
  sh1 <- strheight(s1)
  sw1 <- strwidth(s1)
  sh2 <- strheight(s2)
  sw2 <- strwidth(s2)

  overlap <- FALSE
  if (x1<x2) 
    overlap <- x1 + sw1 > x2
  else
    overlap <- x2 + sw2 > x1

  if (y1<y2)
    overlap <- overlap && (y1 +sh1>y2)
  else
    overlap <- overlap && (y2+sh2>y1)

  return(overlap)
}
stroverlap(.5,.5,"word", .6,.5, "word")
Karsten W.
  • 17,826
  • 11
  • 69
  • 103
  • well, maybe nearly perfect. It doesn't get the tail of lowercase 'p' correct. – Ian Fellows Jun 04 '11 at 20:07
  • This assumes that the coordinates are located at the bottom left corner of each text. Is this true for `text()` in R? or is it actually located in the middle of the text? Will this still work if the latter is true? – acylam Dec 13 '16 at 22:54
2

Package maptools has a function called pointLabel.

Use optimization routines to find good locations for point labels without overlaps.

Roman Luštrik
  • 69,533
  • 24
  • 154
  • 197
1

If you were using base graphics it would be thigmophobe {plotrix}

"Find the direction away from the closest point"

Using lattice, Harrell has offered:

labcurve {Hmisc}

"Label Curves, Make Keys, and Interactively Draw Points and Curves"

IRTFM
  • 258,963
  • 21
  • 364
  • 487
  • I don't see how either of these can be used to figure out if two pieces of text overlap. – Ian Fellows Jun 04 '11 at 02:50
  • They can't, but they're generally useful tools for doing this sort of thing. Not directly answering your question but possibly handy for other people who are browsing here in the future. `labcurve` in particular has some machinery for plotting labels while avoiding overplotting – Ben Bolker Jun 04 '11 at 19:14