[R] Adding a legend to R graph device with several plots (no to individual plots!)

Duncan Murdoch murdoch at stats.uwo.ca
Thu Sep 4 15:58:41 CEST 2008


On 9/4/2008 9:35 AM, Nelson Villoria wrote:
> Dear Users, I already posted this question: it either went unnoticed,
> or it is to basic (if this is so, please sent me a hint).
> 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?

The likely reason you didn't get a reply is because you used 
smartlegend(), which I believe comes from gplots.  This means only 
people who know gplots well will answer.

To do this using legend(), try this:

par(xpd=NA)
legend(locator(), c("1995","2006"), lty=2:1)

This will allow you to place the legend manually whereever you like on 
the page.  If you want to code a particular position for re-use later, 
run locator() on its own, and save the location.  (You will probably 
want to use grconvertX and grconvertY to change these into ndc 
coordinates.  For example, this looks okay to me:

par(xpd=NA)
legend(grconvertX(0.44, "ndc", "user"),
        grconvertY(0.55, "ndc", "user"),
        c("1995","2006"), lty=2:1)

You might want to wrap this in a nice "mlegend()" function to save some 
typing.

Duncan Murdoch



More information about the R-help mailing list