图例位置基于 ggplot2 中的坐标

Legend position based on coordinates in ggplot2

使用ggplot2legend.position(和legend.justification),两个可用参数表示图例的相对位置,但是如果我想根据图例定位怎么办情节的坐标? 我找不到办法。

这很奇怪,因为 annotate 给出了允许此类事情的 x 和 y 参数。

这是一些玩具数据

library(ggplot2)

ggplot(data = mtcars, aes(x = mpg,y = disp,color = factor(cyl))) +
  geom_point() +
  theme(legend.position = c(0.01,0.01),
        legend.justification = c(0,0))

给出:

如果我希望图例的左下角位于坐标 (10,100) 上怎么办?

我认为没有简单的方法可以做到这一点。我能想到的唯一方法是构建绘图对象以提取轴的范围,以便将 (10, 100) 转换为可与图例位置一起使用的相对坐标。不可否认,这很hacky...

library(tidyverse)

p <- ggplot(data = mtcars, aes(x = mpg, y = disp, color = factor(cyl))) +
  geom_point()

ranges <- ggplot_build(p) %>% 
  pluck("layout", "panel_params", 1) %>% 
  `[`(c("x.range", "y.range"))

x <- (10 - ranges$x.range[1]) / (ranges$x.range[2] - ranges$x.range[1])
y <- (100 - ranges$y.range[1]) / (ranges$y.range[2] - ranges$y.range[1])

p + theme(legend.position = c(x, y), legend.justification = c(0, 0))

reprex package (v1.0.0)

创建于 2021-07-21