Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finding the bounding box of plotted text

Tags:

r

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)
like image 901
Ian Fellows Avatar asked Jun 04 '11 02:06

Ian Fellows


3 Answers

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")
like image 55
Karsten W. Avatar answered Oct 22 '22 01:10

Karsten W.


Package maptools has a function called pointLabel.

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

like image 2
Roman Luštrik Avatar answered Oct 22 '22 00:10

Roman Luštrik


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"

like image 1
IRTFM Avatar answered Oct 22 '22 01:10

IRTFM