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)))
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")
  1. create a custom layout, create the plot, then create a dummy plot with no drawing and place the legend in it
#(inspired by )
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)
# other plotting functions ...
# this is the legend part 
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