ggplot2中geom_point的NPC坐标

如何获取 ggplot geom_point x y 坐标,其中框架是整个绘制的图像吗?

我可以使用以下 geom_point 创建一个 ggplot

library(ggplot2)

my.plot <- ggplot(data.frame(x = c(0,0.456,1),y = c(0,0.123,1))) +
             geom_point(aes(x,y),color = "red")

这给出了:

ggplot2中geom_point的NPC坐标

通过将其转换为 grob ,我可以提取有关此 ggplot 的一些其他信息,例如紫色箭头标记的相对于绘图面板的坐标。但是,这会忽略轴占用的空间。

my.grob <- ggplotGrob(my.plot)
my.grob$grobs[[6]]$children[[3]]$x
# [1] 0.0454545454545455native 0.46native 0.954545454545454native 
my.grob$grobs[[6]]$children[[3]]$y
# [1] 0.0454545454545455native 0.157272727272727native 0.954545454545454native

从绿色图像标记的整个图像的左下角开始测量时,如何获取 x y 坐标的值?

如果可能,我希望该解决方案考虑到 ggplot theme 。添加像+ theme_void()这样的 theme 会影响轴,并且还会相对于整个绘制的图像移动点的位置。

更新: 我意识到轴的字体大小会根据绘图的宽度和高度而变化,从而影响绘图面板的相对大小。因此,以 npc 单位提供位置而不定义 plot width plot height 并非易事。如果可能,根据图宽图高给出 geom_points 的位置。

huangchaoqi 回答:ggplot2中geom_point的NPC坐标

调整ggplot的大小时,面板中元素的位置不在npc空间中的固定位置。这是因为绘图中的某些组件具有固定的大小,而其中某些组件(例如面板)会根据设备的大小而更改尺寸。

这意味着任何解决方案都必须考虑设备尺寸,如果要调整绘图尺寸,则必须再次运行计算。话虽如此,对于大多数应用程序(包括您的应用程序而言),这不是问题。

另一个困难是要确保在面板grob中标识正确的grob,很难看到如何轻松地将其概括。在您的示例中使用列表子集函数[[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 package(v0.3.0)于2020-03-25创建

本文链接:https://www.f2er.com/2601436.html

大家都在问