r - 绘制R中quickhull算法给出的凸包(convhulln函数)

标签 r plot geometry convex-hull qhull

我需要在 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 中的起始/终止边对,因此我们将构建所​​述顶点对集:

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)

enter image description here

但是,它们不是“顺序”:

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")

enter image description here

因此,如果您想在这些点周围有一条路径或多边形(这是匿名用户评论/链接的意思),我们需要按顺序排列它们(对它们进行排序)。

我们可以顺时针排序:

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")

enter image description here

关于r - 绘制R中quickhull算法给出的凸包(convhulln函数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48249540/

相关文章:

python - Bokeh 图为空

sql - R 和 MSSQL - 与临时表的通信(在 channel 上找不到表)

r - 使用 ggplot 将变化绘制为值之间的条形图

matlab - 如何在 Matlab R2012b 的绘图中获取斯堪的纳维亚字母 ä 和 ö

sqlalchemy - sqlacodegen 几何类型问题

c++ - 具有连续结果的夹角

language-agnostic - 确定弯曲、拉长区域的中线

sql - 连接到 MS SQL Server 时的 RODBC 临时表问题

Shiny 中的 renderDataTable 未正确渲染输出

python - 我想在 gnuplot 的文本文件中绘制一个具有给定 4 个坐标的矩形。矩形可能与 x 轴成一定角度