调整ggplot的大小时,面板中元素的位置不在npc空间中的固定位置。这是因为绘图中的某些组件具有固定的大小,而其中某些组件(例如面板)会根据设备的大小而更改尺寸。
这意味着任何解决方案都必须考虑设备尺寸,如果要调整图的大小,则必须再次运行计算。话虽如此,对于大多数应用程序(包括您的应用程序而言),这不是问题。
另一个困难是要确保在面板组中识别出正确的组,并且很难看到如何轻松地将其概括。使用列表子功能[[6]],并[[3]]在您的例子并不推广到其他地块。
无论如何,此解决方案的工作方式是:测量面板大小和gtable中的位置,然后将所有大小转换为毫米,然后再除以以毫米为单位的绘图尺寸以转换为npc空间。我试图通过按名称而不是数字索引提取面板和点来使其更加通用。
library(ggplot2)
library(grid)
require(gtable)
get_x_y_values <- function(gg_plot)
{
  img_dim      <- grDevices::dev.size("cm") * 10
  gt           <- ggplot2::ggplotGrob(gg_plot)
  to_mm        <- function(x) grid::convertUnit(x, "mm", valueOnly = TRUE)
  n_panel      <- which(gt$layout$name == "panel")
  panel_pos    <- gt$layout[n_panel, ]
  panel_kids   <- gtable::gtable_filter(gt, "panel")$grobs[[1]]$children
  point_grobs  <- panel_kids[[grep("point", names(panel_kids))]]
  from_top     <- sum(to_mm(gt$heights[seq(panel_pos$t - 1)]))
  from_left    <- sum(to_mm(gt$widths[seq(panel_pos$l - 1)]))
  from_right   <- sum(to_mm(gt$widths[-seq(panel_pos$l)]))
  from_bottom  <- sum(to_mm(gt$heights[-seq(panel_pos$t)]))
  panel_height <- img_dim[2] - from_top - from_bottom
  panel_width  <- img_dim[1] - from_left - from_right
  xvals        <- as.numeric(point_grobs$x)
  yvals        <- as.numeric(point_grobs$y)
  yvals        <- yvals * panel_height + from_bottom
  xvals        <- xvals * panel_width + from_left
  data.frame(x = xvals/img_dim[1], y = yvals/img_dim[2])
}
现在我们可以用您的示例对其进行测试:
my.plot <- ggplot(data.frame(x = c(0, 0.456, 1), y = c(0, 0.123, 1))) +
             geom_point(aes(x, y), color = "red")
my.points <- get_x_y_values(my.plot)
my.points
#>           x         y
#> 1 0.1252647 0.1333251
#> 2 0.5004282 0.2330669
#> 3 0.9479917 0.9442339
我们可以使用我们的值作为npc坐标,通过在红色点上绘制一些点杂点来确认这些值是正确的:
my.plot
grid::grid.draw(pointsGrob(x = my.points$x, y = my.points$y, default.units = "npc"))

由reprex包(v0.3.0)创建于2020-03-25