Legend placement, ggplot, relative to plotting region

后端 未结 4 662
日久生厌
日久生厌 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:54

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

    enter image description here

    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)
    

    enter image description here

提交回复
热议问题