【问题标题】:Absolute positioning of rasterGrobs in gtable cells栅格 Grob 在表格单元格中的绝对定位
【发布时间】:2016-05-26 02:11:05
【问题描述】:

我一直试图在 gtable 单元格中指定 rasterGrobs 的绝对位置,但没有成功。我希望能够使图像的范围与 y 轴上的值对齐。该脚本将钻芯图像与 ggplot2 刻面中绘制的多传感器数据对齐。例如,一个特定的射线照片核心图像需要其顶部为 192 毫米,底部为 1482 毫米,但我希望比例尺从 0 到 1523 毫米。请参阅包含的链接以获取我正在做的示例,但为简单起见,我仅在此处发布了 MWE。是否可以在 gtable 单元格内指定 rasterGrob 的绝对位置?

sample of intended output

就下面的 MWE 而言,到目前为止,我唯一的解决方案是使用rasterGrob() 时设置的相对位置移动Rlogo.png。使用"native" 坐标似乎也不是我需要的。同样,我无法理解gtable_add_grob() 中调用的位置参数。

library(png)
library(ggplot2)
library(gtable)

# read Image
img <- readPNG(system.file("img", "Rlogo.png", package = "png"))

# convert to rastergrob                 
g <- rasterGrob(img, y = unit(0.5, "npc"), x = unit(0.5, "npc"))

# create plot
tp <- qplot(1:5, 1:5, geom="blank") + scale_y_reverse()

# convert plot to gtable
tt <- ggplot_gtable(ggplot_build(tp))

# add column to gtable to hold image
tt <- gtable_add_cols(tt, tt$width[[.5*4]], 3)

# add grob to cell 3, 4
tt <- gtable_add_grob(tt,g,3,4)

# render
grid.draw(tt)

在提出使用 rasterGrob 将图像添加到 ggplot 中的面板的解决方案之前进行了大量搜索。也许有人可以提出更优雅的解决方案?

【问题讨论】:

  • 菜鸟的建议:与gtable_show_layout(tt)友好
  • 是的,谢谢 Edward R. Mazurek。我一直在使用它来获得正确的新列位置。但是我看不到所有文本覆盖的测量信息。是否可以设置一些参数使其更具可读性?

标签: r ggplot2 gtable


【解决方案1】:

grob 可以设置它在单元格中的位置,如下图所示

library(gridExtra)
library(grid)
library(gtable)

# quick shortcut to create a 2x2 gtable filled with 4 rectGrobs
tg <- arrangeGrob(grobs=replicate(4, rectGrob(), FALSE))

# red rect of fixed size with default position (0.5, 0.5) npc
rg1 <- rasterGrob("red", width=unit(1,"cm"), height=unit(1,"cm"))
# blue rect with specific x position (0) npc, left-justified
rg2 <- rasterGrob("blue", width=unit(1,"cm"), height=unit(1,"cm"), 
                  x = 0, hjust=0)
# green rect at x = 1cm left-justified, y=-0.5cm from middle, top-justified
rg3 <- rasterGrob("green", width=unit(1,"cm"), height=unit(1,"cm"), 
                  x = unit(1,"cm"), y=unit(0.5, "npc") - unit(0.5, "cm"), 
                  hjust=0, vjust=1)

# place those on top 
tg <- gtable_add_grob(tg, rg1, 1, 2, z = Inf, name = "default")
tg <- gtable_add_grob(tg, rg2, 1, 2, z = Inf, name = "left")
tg <- gtable_add_grob(tg, rg3, 1, 2, z = Inf, name = "custom")
grid.newpage()
grid.draw(tg)

【讨论】:

  • 谢谢巴蒂斯特!我会试一试并报告。似乎使用此解决方案,我需要使用 gtable_show_layout 才能实际查看绘图和单元格尺寸。我实际上无法阅读提供的一些文字。你知道让 gtable_show_layout 更具可读性的方法吗?
  • grid.show.layout(gtable:::gtable_layout(tg), vp = viewport(gp = gpar(cex=2))) 也许?
  • 再次感谢@baptiste,您的回复给了我很大的帮助,尽管现在我还有很多问题可以在另一个问题中提出。顺便说一句,您在上述评论中关于调整 cex 的建议效果很好。
猜你喜欢
  • 2012-06-09
  • 2012-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多