且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

R中图像矩阵绘制矩形的效率

更新时间:2023-12-01 11:14:34

我不知道是否有 rect的矢量化版本但你可以使用矢量化的 poylygon 。你只需要在矩形之间添加NA。这个答案的灵感来自于此处的优秀答案。

I don't know if there is a vectorized version of rect but you can use poylygon which is vectorized . You need just to add NA between rectangles. This answer is inspired from the excellent answer here.

cuts <- function(x)
{
  n <- length(x) %/% 4
  map <- rep(c(rep(TRUE,4),FALSE), n)
  result <- rep(NA, n*5)
  result[map] <- x
  result
}


n <- 2000

xbottom <- runif(n)
ybottom <- runif(n)
xtop <- xbottom+runif(n)
ytop <- ybottom+runif(n)

x <- cbind(xbottom,xbottom,xtop,xtop)
y <- cbind(ybottom,ytop,ytop,ybottom)
cols <- heat.colors(n)[order(x[,1])]
plot(0, xlim=c(min(x),max(x)), ylim=c(min(y),max(y)))
polygon(x=cuts(t(x)), y=cuts(t(y)), col=cols)

这将创建2000矩形瞬间。

This will creates the 2000 rectangles instantaneously.