ggplot2:将图例移到角落但将其保留在边距中?

ggplot2: Move legend to corner but keep it in margin?

我想将我的 ggplot2 图例移到角落,但在情节本身内。所以它应该仍然在边缘,而不是在中心。我发现的唯一选项是选择 "top," "right," 等,或者在 绘图本身中使用自定义坐标

例如,拍摄这张图片:

想象一下将图例从当前位置直接向下滑动到右下角。

例如,我尝试将图例位置设置为 c(12, 2),但它就消失了。

设置为"right"就是当前图片的样子,但是我需要图例下滑到"bottom-right."

您可以扩大图边距,然后将图例位置设置到图外的某个位置。

创建您的数据:

dat = data.frame(x=1:10, y=10:1, type=rep(c('a', 'b'), each=5))

使用 theme 中的 plot.marginlegend.position 元素。首先用你的边距创建一个 unit 对象:

margins = unit(c(1, 4, 1, 1), 'lines')

然后用边距和图例位置调用 ggplot。

ggplot(dat, aes(x, y, color=type)) + 
    geom_point() +
    theme(plot.margin=margins,
          legend.position=c(1.075, 0))

(图例位置通常设置在0和1之间(使用归一化父坐标),而不是绘图的实际x和y坐标。)