如何在 ggplot2 中为矩形 rasterGrob 添加边框?

我正在尝试向已添加到 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 查看器中看起来像这样:

如何在 ggplot2 中为矩形 rasterGrob 添加边框?

因为我已经从光栅中指定了 x 和 y 坐标以及宽度,所以很容易为边界坐标复制这些。但是,由于我没有指定任何高度,因此我不确定找出 npc 设置边框高度的最佳方法。我没有设置高度,因为我想根据 .png 尺寸自动保留标志的任何纵横比。

我查看了一些可能对网格有帮助的函数,例如 resolveRasterSize,它说你可以

当一个或两个都被确定时,确定一个光栅grob的宽度和高度 没有明确给出

还有一些关于方面/视口的东西,我不太熟悉它如何影响在 ggplot2 中创建的图。在带有 rectgrobheight = resolveRasterSize(g)$height 中,情节最终看起来像:

如何在 ggplot2 中为矩形 rasterGrob 添加边框?

边框与图像不匹配。我还注意到使用 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)

如何在 ggplot2 中为矩形 rasterGrob 添加边框?

zuoduzu 回答:如何在 ggplot2 中为矩形 rasterGrob 添加边框?

正如您正确确定的那样,问题在于您的 rectGrob 的尺寸将受到绘图窗口缩放的不同影响,而不是您的 rasterGrob 的尺寸。您可以使用一点数学来解决这个问题,以校正光栅和绘图窗口的纵横比。唯一的缺点是在调整绘图窗口大小时必须重新运行计算。对于大多数应用程序,这不是主要问题。例如,要保存为 16 x 9 png 文件,您可以执行以下操作:

img <- readPNG("gb.png")

g <- rasterGrob(img,x = unit(0.5,"npc"),y = unit(0.5,width = unit(0.4,"npc"))

img_aspect <- dim(g$raster)[1] / dim(g$raster)[2]
dev_aspect <- 16/9
rect_aspect <- dev_aspect * img_aspect

border <- rectGrob(x = unit(0.5,width = g$width,height = g$width * rect_aspect,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))

ggsave(filename = "my_example.png",plot = myplot,width = 16,height = 9)

导致:

my_example.png

enter image description here

如果你想让边框适合 R Studio 中的当前设备,那么你可以使用

dev_aspect <- dev.size()[1]/dev.size()[2]

如果您想要一个矩形来缩放绘图中发生的任何情况,那么可以通过创建一个仅包含黑色边框的 rasterGrob 来实现。

例如,如果您这样做:

border <- g$raster
border[] <- "#00000000"
border[1:2,] <- "#000000FF"
border[,1:2] <- "#000000FF"
border[nrow(border) + seq(-1,0),ncol(border) + seq(-1,0)] <- "#000000FF"

border <- rasterGrob(border,"npc"))

myplot <- ggplot() +
  annotation_custom(g) +
  annotation_custom(border) +
  scale_x_continuous(limits = c(0,1))

然后 myplot 将在标志周围显示一个黑色边框,该边框随着重新缩放而持续存在。

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

大家都在问