繁体   English   中英

由R(convhulln函数)中的quickhull算法给出的凸包

[英]Plot convex hull given by quickhull algorithm in R (convhulln function)

我需要在R中绘制由quickhull算法给出的凸包。这是一个例子。

library(geometry)
x1 <- rnorm(100, 0.8, 0.3)
y1 <- rnorm(100, 0.8, 0.3)
ConVexHull<-convhulln(cbind(x1,y1),"FA")

ConVexHull $ hull给出了一个m维索引矩阵,其中每行定义一个暗淡的“三角形”。

我知道如何使用chull函数进行绘图,但我不确定chull是否给出了convhulln给出的相同的船体

  Plot_ConvexHull<-function(xcoord, ycoord, lcolor){
  hpts <- chull(x = xcoord, y = ycoord)
  hpts <- c(hpts, hpts[1])
  lines(xcoord[hpts], ycoord[hpts], col = lcolor)
} 
xrange <- range(c(x1))
yrange <- range(c(y1))
par(tck = 0.02, mgp = c(1.7, 0.3, 0))
plot(x1, y1, type = "p", pch = 1, col = "black", xlim = c(xrange), ylim =    c(yrange))
Plot_ConvexHull(xcoord = x1, ycoord = y1, lcolor = "black")

可重复的例子:

library(geometry)

set.seed(0)

x1 <- rnorm(100, 0.8, 0.3)
y1 <- rnorm(100, 0.8, 0.3)

xdf <- data_frame(x1, y1)

(ConVexHull <- convhulln(cbind(x1,y1), "FA"))
## $hull
##      [,1] [,2]
## [1,]   63   59
## [2,]   10   53
## [3,]   10   63
## [4,]   80   59
## [5,]   80   15
## [6,]   37   53
## [7,]   37   15
## 
## $area
## [1] 4.258058
## 
## $vol
## [1] 1.271048

那些是$hull中的from / to edge对,所以我们将构建一组顶点对:

data.frame(
  do.call(
    rbind,
    lapply(1:nrow(ConVexHull$hull), function(i) {
      rbind(xdf[ConVexHull$hull[i,1],], xdf[ConVexHull$hull[i,2],])
    })
  )
) -> h_df

而且,证明它们确实是正确的:

ggplot() +
  geom_point(data=xdf, aes(x1, y1), color="red") +
  geom_point(data=h_df, aes(x1, y1), shape=21, fill=NA, color="black", size=3)

在此输入图像描述

但是,它们不是 “有序”的:

ggplot() +
  geom_point(data=xdf, aes(x1, y1), color="red") +
  geom_point(data=h_df, aes(x1, y1), shape=21, fill=NA, color="black", size=3) +
  geom_path(data=h_df, aes(x1, y1), color="blue")

在此输入图像描述

因此,如果您希望在点周围有一个路径或多边形(这是匿名用户的注释/链接的含义),我们需要按顺序对它们进行排序(对它们进行排序)。

我们可以顺时针排序它们:

h_df <- h_df[order(-1 * atan2(h_df$y1 - mean(range(h_df$y1)), h_df$x1 - mean(range(h_df$x1)))),]
h_df <- rbind(h_df, h_df[1,])

(删除-1反向)

而且,我们有一个可爱的外包装:

ggplot() +
  geom_point(data=xdf, aes(x1, y1), color="red") +
  geom_point(data=h_df, aes(x1, y1), shape=21, fill=NA, color="black", size=3) +
  geom_path(data=h_df, aes(x1, y1), color="blue")

在此输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM