4

我想在 R 中的一个绘图上绘制 60,000 多个非重叠三角形(非结构化三角形网格的一部分)。目前,每个绘图需要 15-20 分钟,这使得它无法用于制作动画。例如,

n <- 100 #Except replace this with 60,000
x <- matrix(runif(3*n), n)
y <- matrix(runif(3*n), n)
cols <- heat.colors(n)[order(x[,1])]
poly <- function(i) {polygon(x[i,], y[i,], col=cols[i])}
plot(0, xlim=c(min(x),max(x)), ylim=c(min(y),max(y)))
sapply(1:n, poly)

是否可以在每个多边形之后抑制多边形()重绘?我猜这是最耗时的步骤,并且在手册页中没有提到。对于如何实现这一点的替代建议将不胜感激。谢谢你。

4

2 回答 2

5

您可以将多个多边形传递给polygon. 您所要做的就是与NA. 这是一个代码:

cuts <- function(x)
{
    n <- length(x) %/% 3

    map <- rep(c(TRUE,TRUE,TRUE,FALSE), n)

    result <- rep(NA, n*4)

    result[map] <- x

    result
}


set.seed(1234)

n <- 10000
x <- matrix(runif(3*n), n)
y <- matrix(runif(3*n), n)
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)

工作速度快。我已经测试了控制种子并与您的代码生成的图进行比较。

于 2013-03-20T21:15:11.507 回答
2

grid.polygon这里是使用包的矢量化解决方案grid。我使用latticejust 来绘制场景(xyplot(0~0)~ plot(0))。

library(lattice)
library(grid)
xyplot(0~0, xlim=c(min(x),max(x)), ylim=c(min(y),max(y)),
       panel=function(...)
       {
         grid.polygon(x  = as.vector(t(x)),
                      y  = as.vector(t(y)),
                      id = rep(1:n,each=3),
                      gp=gpar(fill=cols),
                      def='native')         
       })

在我的普通 PC 中生成 60000 个多边形需要不到 30 秒的时间。

于 2013-03-20T21:05:44.453 回答