[R] Positioning legends outside the plot region
Marco Albani
malbani at fas.harvard.edu
Fri Jul 18 19:30:21 CEST 2003
Hello,
I understand this issue has already been discussed
http://maths.newcastle.edu.au/~rking/R/help/01c/3763.html
but there is one point I am trying to understand better.
I want to lace a legend below the plotting region.
Right now I do
## increase size of the right hand border (secondary axis)
## and bottom border (legend)
old.mar <- par("mar")
old.mar[1] <- 7.1
old.mar[4] <- 7.1
old.par <- par(mar=old.mar)
plot(data$t, data$w, type="l",
xlab =x.lab, ylab = y.lab, col="black", lwd=2,
...)
## Plot the fluxes on a secondary axis
x <- range(data$w)
y <- range(c(data$rain,data$uptake,data$perc))
K <- x[1] - y[1]*(x[2]-x[1])/(y[2]-y[1])
R <- (x[2]-x[1])/(y[2]-y[1])
y.seq <- pretty(y)
lines(data$t, (K + R * data$uptake) , col ="green")
axis(4, at = (K + R * y.seq), labels = y.seq)
mtext(y2.lab, side=4, line=2)
title(main = paste("Soil Water dynamics for site\n",data$site[1]),
sub = NULL, xlab = NULL, ylab = NULL,
line = NA, outer = FALSE)
## 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])
y <- par("usr")[3] - 1
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,
)
par(old.par)
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?
--
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
http://www.people.fas.harvard.edu/~malbani
More information about the R-help
mailing list