Legend placement, ggplot, relative to plotting region

ggplot2, r

Solution

Update: `opts` has been deprecated. Please use `theme` instead, as described in this answer.

The placement of the guide is based on the plot region (i.e., the area filled by grey) by default, but justification is centered. So you need to set left-top justification:

ggplot(mtcars, aes(x=wt, y=mpg, colour=cyl)) + geom_point(aes(colour=cyl)) + 
  opts(legend.position = c(0, 1), 
       legend.justification = c(0, 1), 
       legend.background = theme_rect(colour = NA, fill = "white"),
       title="Legend placement makes me happy")

If you want to place the guide against the whole device region, you can tweak the gtable output:

p <- ggplot(mtcars, aes(x=wt, y=mpg, colour=cyl)) + geom_point(aes(colour=cyl)) + 
  opts(legend.position = c(0, 1), 
       legend.justification = c(0, 1), 
       legend.background = theme_rect(colour = "black"),
       title="Legend placement makes me happy")

gt <- ggplot_gtable(ggplot_build(p))
nr <- max(gt$layout$b)
nc <- max(gt$layout$r)
gb <- which(gt$layout$name == "guide-box")
gt$layout[gb, 1:4] <- c(1, 1, nr, nc)
grid.newpage()
grid.draw(gt)

Problem

Problem here is a bit obvious I think. I'd like the legend placed (locked) in the top left hand corner of the 'plotting region'. Using c(0.1,0.13) etc is not an option for a number of reasons. Is there a way to change the reference point for the co-ordinates so they are relative to the plotting region? ``` mtcars$cyl <- factor(mtcars$cyl, labels=c("four","six","eight")) ggplot(mtcars, aes(x=wt, y=mpg, colour=cyl)) + geom_point(aes(colour=cyl)) + opts(legend.position = c(0, 1), title="Legend placement makes me sad") ``` Cheers

Original source