[R] Adding a common legend to an arrangement of plots

Nelson Villoria nvilloria at gmail.com
Sun Aug 24 02:50:16 CEST 2008

Dear Users, I would like to know if there is a way to add a common
legend to an arrangement of plots. In the example below, I get four
plots in my device. each one has a density for 1995 and one for 2006.
I have found that using legend or smartlegend I can add a legend to
each plot, but I am looking for something in the spirit of mtext. That
is, putting the legend anywhere I want on the device. In my situation
I have:

par(mfrow=c(2,2), ann = FALSE)
p.names <- c("1","2","3","4")
lapply(p.names, function(x) {
 d1 <- density(rnorm(100,0,1))
 d2 <- density(rnorm(100,.3,1.2))
 plot(range(d1$x, d2$x), range(d1$y, d2$y), type = "n", xlab = NULL,
ylab = NULL)
   lines(d1, col = "black", lty = 2)
   lines(d2, col = "black", lty = 1)
mtext("Learning R the hard way", side = 1, line=-1.5, outer=TRUE)
smartlegend(x= "center", y="top", c("1995","2006"), lty=2:1)

the last line puts the legend on the lower-right plot. I'd like to put
it in the middle - or top of the device. Any suggestion?



More information about the R-help mailing list