图例放置,ggplot,相对于绘图区域 [英] Legend placement, ggplot, relative to plotting region
问题描述
我认为这里的问题有点显而易见。我希望将这个图例置于(锁定)在绘图区域的左上角。使用c(0.1,0.13)等不是一种选择,原因很多。
有没有办法改变坐标的参考点,所以它们是相对于绘图区域而言?
mtcars $ cyl < - factor(mtcars $ cyl,labels = c(four, (x = wt,y = mpg,color = cyl))+ geom_point(aes(color = cyl))+
opts(legend .position = c(0,1),title =图例位置令我难过)
< img src =https://i.stack.imgur.com/i4H6s.pngalt =在这里输入图片描述>
干杯
更新: opts
已被弃用。请使用主题
代替,如在此答案中所述。
默认情况下,指南的位置基于绘图区域(即用灰色填充的区域),但对齐以居中。
所以你需要设置左上对齐:
$ $ $ $ $ $ $ $ $ ggplot(mtcars,aes(x = wt,y = (0,1),
legend.justification = c(0,1),
legend.background = theme_rect(color = NA,fill =white),
title =图例位置让我开心)
如果要将指南放在整个设备区域中,可以调整gtable输出:
<$ c (x = wt,y = mpg,color = cyl))+ geom_point(aes(color = cyl))+
opts(legend.position = c(0 ,1),
legend.justification = c(0,1),
legend.background = theme_rect(color =black),
title =图例位置让我开心)
gt< - ggplot_gtable(ggplot_build(p))
nr< - max(gt $ layout $ b)
nc& lt; -max(gt $ layout $ r)
gb< - 其中(gt $ layout $ name ==guide-box)
gt $ layout [gb,1:4]< - c(1,1,nr,nc)
grid.newpage()
grid.draw(gt)
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
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)
这篇关于图例放置,ggplot,相对于绘图区域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!