Legend placement, ggplot, relative to plotting region

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

Just to expand on kohske’s answer, so it’s bit more comprehensive for the next person to stumble upon it.

mtcars$cyl <- factor(mtcars$cyl, labels=c("four","six","eight"))
library(gridExtra)

a <- ggplot(mtcars, aes(x=wt, y=mpg, colour=cyl)) + geom_point(aes(colour=cyl)) + 
opts(legend.justification = c(0, 1), legend.position = c(0, 1), title="Legend is top left")
b <- ggplot(mtcars, aes(x=wt, y=mpg, colour=cyl)) + geom_point(aes(colour=cyl)) + 
opts(legend.justification = c(1, 0), legend.position = c(1, 0), title="Legend is bottom right")
c <- ggplot(mtcars, aes(x=wt, y=mpg, colour=cyl)) + geom_point(aes(colour=cyl)) + 
opts(legend.justification = c(0, 0), legend.position = c(0, 0), title="Legend is bottom left")
d <- ggplot(mtcars, aes(x=wt, y=mpg, colour=cyl)) + geom_point(aes(colour=cyl)) + 
opts(legend.justification = c(1, 1), legend.position = c(1, 1), title="Legend is top right")

grid.arrange(a,b,c,d)

enter image description here

Leave a Comment