I am trying to draw a bounding box around different polygon shapes in R with the grid functions grobX and gorbY. The polygons are drawn using the grid primitive function polygonGrob or grid.polygon.
x <- c(0.65, 0.614906666467847, 0.42604722665004, 0.425, 0.359046106882114,
0.259046106882114, 0.425, 0.526047226650039, 0.614906666467847)
y <- c(0.5, 0.692836282905962, 0.895442325903662, 0.759807621135332,
0.602606042997701, 0.397393957002299, 0.240192378864668, 0.204557674096338,
0.307163717094038)
library(grid)
pg <- polygonGrob(x=x, y=y,
default.units = "native",
gp=gpar(fill="gray"))
pntg <- pointsGrob(x=x, y=y,
pch = 20,
size = grid::unit(3, "mm"),
default.units = "native",
gp=gpar(col="red"))
rcg <- rectGrob(x=0.33, height=0.7, width=0.2,
gp=gpar(fill="gray"))
I am able to fetch the outer dimensions with regular shapes like a rectangle. But with an irregular polygon shape, the values are off.
pushViewport(plotViewport(c(5, 4, 2, 2)))
pushViewport(dataViewport(x, y))
grid.rect()
grid.xaxis()
grid.yaxis()
grid.draw(pg)
grid.draw(pntg)
x1 <- grid::convertWidth(grid::grobX(pg, "west"), "npc", TRUE)
x2 <- grid::convertWidth(grid::grobX(pg, "east"), "npc", TRUE)
y1 <- grid::convertHeight(grid::grobY(pg, "south"), "npc", TRUE)
y2 <- grid::convertHeight(grid::grobY(pg, "north"), "npc", TRUE)
grid::grid.polyline(x = c(x1, x1, x2, x2, x1),
y = c(y1, y2, y2, y1, y1),
default.units = "npc",
gp = gpar(col = "blue"))
pushViewport(plotViewport(c(5, 4, 2, 2)))
pushViewport(dataViewport(x, y))
grid.rect()
grid.xaxis()
grid.yaxis()
grid.draw(rcg)
x1 <- grid::convertWidth(grid::grobX(rcg, "west"), "npc", TRUE)
x2 <- grid::convertWidth(grid::grobX(rcg, "east"), "npc", TRUE)
y1 <- grid::convertHeight(grid::grobY(rcg, "south"), "npc", TRUE)
y2 <- grid::convertHeight(grid::grobY(rcg, "north"), "npc", TRUE)
grid::grid.polyline(x = c(x1, x1, x2, x2, x1),
y = c(y1, y2, y2, y1, y1),
gp = gpar(col = "red"))
How to get the accurate outer dimensions from an irregular polygon grob ?

I'm not sure why you are using
grobXandgrobYhere. You can simply get the minimum and maximum values of the co-ordinates and convert them to npc withconvertXandconvertY