我正在尝试向已添加到 ggplot 的矩形 png 图像 (found here) 添加边框,并使用 npc 指定定位。
library(png)
library(grid)
library(ggplot2)
img <- readPNG("gb.png")
g <- rasterGrob(img,x = unit(0.5,"npc"),y = unit(0.5,width = unit(0.4,"npc"))
border <- rectGrob(x = unit(0.5,# height = resolveRasterSize(g)$height,gp = gpar(lwd = 2,col = "black",fill="#00000000"))
myplot <- ggplot() +
annotation_custom(g) +
annotation_custom(border) +
scale_x_continuous(limits = c(0,1)) +
scale_y_continuous(limits = c(0,1))
在 RStudio 查看器中看起来像这样:
因为我已经从光栅中指定了 x 和 y 坐标以及宽度,所以很容易为边界坐标复制这些。但是,由于我没有指定任何高度,因此我不确定找出 npc 设置边框高度的最佳方法。我没有设置高度,因为我想根据 .png 尺寸自动保留标志的任何纵横比。
我查看了一些可能对网格有帮助的函数,例如 resolveRasterSize
,它说你可以
当一个或两个都被确定时,确定一个光栅grob的宽度和高度 没有明确给出
还有一些关于方面/视口的东西,我不太熟悉它如何影响在 ggplot2 中创建的图。在带有 rectgrob
的 height = resolveRasterSize(g)$height
中,情节最终看起来像:
边框与图像不匹配。我还注意到使用 resolveRasterSize
创建的高度变量被赋予了一个带有英寸而不是 npc 的属性。
如果我调整 Plots 平面的大小,我注意到标志和边框的高度动态变化,有时我可以让它们对齐,但我想要一种更精确的方法来让它们正确对齐,例如如果我在 ggsave 或一些用法中使用不同尺寸进行保存。
我尝试查看其他 grid
函数,例如 convertHeight
,在 height = convertHeight(resolveRasterSize(g)$height,"npc")
中使用 rectGrob
,这似乎总是在 RStudio 的 Plot 窗格中设置正确的边框,但是如果我调整窗格大小,边框会再次错位,如果我使用 ggsave 保存,它也会错位。
ggsave(filename = "my_example.png",plot = myplot,width = 16,height = 9)