【发布时间】:2019-10-15 09:51:33
【问题描述】:
我的问题和Convert units from npc to native using grid in R有些关系。
我正在尝试找出某些绘图元素的位置,这些元素从 ggplot2 对象(轴、主图等)开始。我找到了以下代码:
rm(list = ls())
library(ggplot2)
library(grid)
library(gtable)
# a dummy plot
g <- ggplot(cars, aes(x = speed, y = dist)) +
geom_point()
g
# a layout of each element
obj <- ggplotGrob(g)
l <- gtable:::gtable_layout(obj)
grid:::grid.show.layout(l)
我需要的所有信息都必须在名为l 的布局对象中。然而,这些物体的高度和宽度相当奇怪。它们通常为零,即使布局有一些绘制!我调整了grid:::grid.show.layout 以打印它正在绘制的大小:
# aside from sprintf and cat a copy of grid:::grid.show.layout
foo <- function(l, newpage = TRUE, vp.ex = 0.8, bg = "light grey",
cell.border = "blue", cell.fill = "light blue", cell.label = TRUE,
label.col = "blue", unit.col = "red", vp = NULL, ...) {
if (!grid:::is.layout(l))
stop("'l' must be a layout")
if (newpage)
grid.newpage()
if (!is.null(vp))
pushViewport(vp)
grid.rect(gp = gpar(col = NULL, fill = bg))
vp.mid <- viewport(0.5, 0.5, vp.ex, vp.ex, layout = l)
pushViewport(vp.mid)
grid.rect(gp = gpar(fill = "white"))
gp.red <- gpar(col = unit.col)
objs <- matrix(list(), l$nrow, l$ncol)
unitType <- "cm"
for (i in 1L:l$nrow) for (j in 1L:l$ncol) {
h <- convertX(x = l$heights[i, top = FALSE], unitTo = unitType)
w <- convertY(x = l$widths[j, top = FALSE], unitTo = unitType)
s1 <- sprintf("s1: i = %d, j = %d, height = %s, width = %s\n", i, j, h, w)
cat(s1)
vp.inner <- viewport(layout.pos.row = i, layout.pos.col = j)
pushViewport(vp.inner)
# an attempt so save the drawn objects
objs[[i, j]] <- grid.rect(gp = gpar(col = cell.border, fill = cell.fill))
if (cell.label)
grid.text(paste0("(", i, ", ", j, ")"), gp = gpar(col = label.col))
if (j == 1)
grid.text(format(l$heights[i, top = FALSE], ...),
gp = gp.red, just = c("right", "centre"), x = unit(-0.05,
"inches"), y = unit(0.5, "npc"), rot = 0)
if (i == l$nrow)
grid.text(format(l$widths[j, top = FALSE], ...),
gp = gp.red, just = c("centre", "top"), x = unit(0.5,
"npc"), y = unit(-0.05, "inches"), rot = 0)
if (j == l$ncol)
grid.text(format(l$heights[i, top = FALSE], ...),
gp = gp.red, just = c("left", "centre"), x = unit(1,
"npc") + unit(0.05, "inches"), y = unit(0.5,
"npc"), rot = 0)
if (i == 1)
grid.text(format(l$widths[j, top = FALSE], ...),
gp = gp.red, just = c("centre", "bottom"), x = unit(0.5,
"npc"), y = unit(1, "npc") + unit(0.05, "inches"),
rot = 0)
popViewport()
}
popViewport()
if (!is.null(vp))
popViewport()
return(objs)
}
运行foo(l) 打印:
s1: i = 1, j = 1, height = 0.193302891933029cm, width = 0.193302891933029cm
...
s1: i = 7, j = 5, height = 0cm, width = 0cm
...
s1: i = 12, j = 9, height = 0.193302891933029cm, width = 0.193302891933029cm
奇怪的是,单步执行 withbrowser 函数显示 i = 7, j = 5 打印出中间最大的矩形,但大小却是 0cm、0cm!原始单位(分别为 1null、1null)。
所以我的问题是,如何获得以 npc/ 原生单位表示的矩形的大小/坐标? 我很高兴遍历整个结构,但我想将每个矩形的单位变成了一些有意义的东西。理想情况下,我会为每个布局元素获取由grid.rect 在 npc 或设备的本机单位中绘制的四个角的位置。
有什么想法吗?
【问题讨论】: