Skip to content
Prev 166920 / 398502 Next

How to get legend outside of plot?

Dear Mike: 

      1.  Might it work to use legend(x = if(median(data) > 
mean(range(data))) "topleft", else "bottomright", ...)? 

      2.  The first two hits to 'RSiteSearch("points outside plot 
region")' suggested setting "par(xpd=TRUE)", then specifying "x" and "y" 
in "legend" appropriately outside the plot region.  For example, 
par(mar=c(5, 4, 4, 11)+0.1, xpd=TRUE) would leave room on the left hand 
side of the plot.  Then legend(max(x), max(y), ...) would put the legend 
top right outside the plot.  The following is a modification of the 
first example from the "legend" help page: 

leg.txt <- c("Setosa     Petals", "Setosa     Sepals",
                  "Versicolor Petals", "Versicolor Sepals")
op <- par(mar=c(5, 4, 4, 11)+.1, xpd=TRUE)
legend(0, -1, leg.txt)
matplot(c(1,8), c(0,4.5), type = "n", xlab = "Length", ylab = "Width",
             main = "Petal and Sepal Dimensions in Iris Blossoms")
legend(9, 4.5, leg.txt, pch = "sSvV", col = c(1, 3))
par(op)

      3.  The "lattice" package offers more control for this kind of 
thing.  This package is quite valuable for multivariate displays of all 
kinds.  Unfortunately, I found it difficult to learn.  For me an 
essential reference is Sarkar (2008) Lattice: Multivariate Data 
Visualization with R (Springer). 


      Hope this helps. 
      Un fuerte abrazo,
      Spencer
Mike Williamson wrote: