[R] Re: Positioning legends outside the plot region

Marco Albani
Fri, 18 Jul 2003 18:54:43 -0000

Marco Albani wrote:
>
> The part I am not happy with is the setting of the y coordinates for the
> legend.
>
> Is there a good way to tie it in with the par("mar")[1] so that I
know
> the legend is place below the title of the x axis of my plot?
>

I answer my own question:


## Set xpd=TRUE, so all plotting is clipped to the figure
## (not the plot) region:
old.par <- par(xpd=TRUE)

#add the legend outside the plot on the bottom, centered on the plot x axis
x <- mean(par("usr")[1:2])

## calculate the ratio of inches to y user coords
in2y <- (par("usr")[4] -
par("usr")[3])/par("pin")[2]

## place y at the bottom of the margin
y <-  par("usr")[3] - par("mai")[1] * in2y

## justify the legend so that is centered in x (xjust=0.5)
## and on top of y (yjust=0)
legend(x,y,
            legend=c("Soil Water",
"Precipitation","Percolation","Uptake"),

col=c("black","blue","red","green"),
            lwd=c(2,1,1,1),
            bty="n", xjust=0.5, ncol=2, yjust=0
      )

par(old.par)


--
Marco Albani, Ph.D.
Postdoctoral Fellow
Dept. of Organismic and Evolutionary Biology
Harvard University
HUH 22 Divinity Avenue
Cambridge, MA
02138-2094 USA

Tel: +1 617 495 1621
Fax: +1 617 495 9484