Legend placement, ggplot, relative to plotting region

后端 未结 4 695
日久生厌
日久生厌 2020-11-28 05:25

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

4条回答
  •  甜味超标
    2020-11-28 05:31

    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

提交回复
热议问题