Problem: you want the legend to appear outside the plotting region (for instance, to avoid collision with the data).

Solutions:

RSiteSearch("legend outside plot")

ggplot2 and lattice offer this layout as the default.

typical ggplot2 call:

 
x <- rnorm(10)
y <- rnorm(10)
 
mdf <- data.frame(x=x, y=y, f=factor(sample(letters[1:2], replace=T)))
head(mdf)
 
qplot(x, y, data=mdf, col=f)

same with lattice:

xyplot(y~x, data=mdf, groups=f, auto.key=list(space="right"))

or raw grid:


In base graphics, the procedure is slightly more complicated as drawing is clipped to the plotting region by default.

Several approaches are possible:

  1. expand the margin with par(), set the clipping off, draw the legend outside
op <- par(mar=c(5, 4, 4, 11)+.1, xpd=TRUE)
plot(x, y)
lines (x, y)
grid() # note that the lines are not clipped anymore!
legend(2, 1, c("a", "b"), pch=1:2, title="this is my legend")
par(op)
  1. create a custom layout, create the plot, then create a dummy plot with no drawing and place the legend in it
 
#(inspired by https://stat.ethz.ch/pipermail/r-help/2007-May/132466.html )
 
layout(matrix(c(1, 2),ncol=2,  byrow=F),widths=c(1,0.5)) # tweak dimensions and layout as needed
 
plot(x, y)
lines (x, y)
grid()
# other plotting functions ...
 
# this is the legend part
plot.new() 
plot.window(c(0,1), c(0,1))
 
legend(0,1, c("a", "b"), pch=1:2, title="this is my legend")
 
tips/graphics-misc/legendoutside.txt · Last modified: 2009/01/14
 
Recent changes RSS feed R Wiki powered by Driven by DokuWiki and optimized for Firefox Creative Commons License