簡體   English   中英

使用“grid”從“R”中的不規則多邊形grob中獲取外部尺寸以繪制邊界框

[英]Fetch outer dimensions to draw a bounding box from an irregular polygon grob in `R` using `grid`

我正在嘗試使用grid函數grobXgorbYR中的不同多邊形形狀周圍繪制一個邊界框。 多邊形是使用grid基元函數polygonGrobgrid.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"))

在此處輸入圖像描述 如何從不規則多邊形 grob 中獲得准確的外部尺寸?

我不確定你為什么在這里使用grobXgrobY 您可以簡單地獲取坐標的最小值和最大值,並使用convertXconvertY將它們轉換為 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM