Problem: you want the legend to appear outside the plotting region (for instance, to avoid collision with the data).
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:
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)
#(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")