[英]Fetch outer dimensions to draw a bounding box from an irregular polygon grob in `R` using `grid`
我正在嘗試使用grid
函數grobX
和gorbY
在R
中的不同多邊形形狀周圍繪制一個邊界框。 多邊形是使用grid
基元函數polygonGrob
或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"))
我能夠獲取具有規則形狀(如矩形)的外部尺寸。 但是對於不規則的多邊形,這些值是關閉的。
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"))
我不確定你為什么在這里使用grobX
和grobY
。 您可以簡單地獲取坐標的最小值和最大值,並使用convertX
和convertY
將它們轉換為 npc
grid.newpage()
pushViewport(plotViewport(c(5, 4, 2, 2)))
pushViewport(dataViewport(x, y))
grid.rect()
grid.xaxis()
grid.yaxis()
grid.draw(pg)
grid.draw(pntg)
x1 <- convertX(min(pg$x), "npc", TRUE)
x2 <- convertX(max(pg$x), "npc", TRUE)
y1 <- convertY(min(pg$y), "npc", TRUE)
y2 <- convertY(max(pg$y), "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"))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.