[R] Placing of legends

Stephen D. Weigand weigand.stephen at charter.net
Sun Nov 5 04:03:44 CET 2006


On Nov 4, 2006, at 1:47 PM, Thevini & Christian Lerch wrote:

> Hello,
>
> placings of legends is sometimes tricky.
> For placing outside the plot region I found locator to be useful.
> Unfortunately, the click defines the upper left corner.
>
> Is there a way to change this corner (say lower right corner)?
>
> Thanks,
>
> Christian
>

You could take advantage of the fact that legend() returns the height 
and width of the legend box and calculate where the top left should be 
given the bottom right. Here's something maybe you can build off of:

mylegend <- function(x.right, y.bottom = NULL, ...) {
     ## allowance for input from locator() or
	xy <- xy.coords(x = x.right, y = y.bottom)
	x.right <- xy$x
	y.bottom <- xy$y

	L <- legend(x = "topleft", plot = FALSE, ...)
	x <- x.right - L$rect$w  # shift left by width of box
	y <- y.bottom + L$rect$h # shift up by height of box
	legend(x = x, y = y, ...)
}

plot(1:10)

### given separate 'x' and 'y'
mylegend(x.right = 10, y.bottom = 2,
        legend = c("Alpha", "Beta"), pch = 1:2, lty = 1:2)

### given locator()-like input
mylegend(list(x=6,y=8), legend = c("Alpha", "Beta"), pch = 1:2)


Hope this helps,

Stephen
Rochester, Minnesota, USA



More information about the R-help mailing list