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 fo
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)