绘制围绕一组点的曲线

ami*_*mit 27 curve r graphics2d

我在飞机上有一套点.它们被划分为子集.我想围绕属于同一子集的点绘制闭合曲线,以便属于子集的点将位于曲线内部,而不属于该子集的点将位于曲线内部.因此,简单的圆形或凸包可能不起作用.

对于初学者,假设我只想在一组点附近有一条平滑的曲线(不要求它排除其他点)

任何想法如何在R?

---后来补充---

我最终看到的是这里的图形精神:https://tex.stackexchange.com/questions/1175/drawing-a-hypergraph - 虽然上下文不是超图,而是给定的点集和那些分区.

the*_*ail 22

好的,这是我认为接近你追逐的答案的一个版本的答案:它使用在GIS论坛上的spline.poly这个答案(https://gis.stackexchange.com/a/24929)创建的功能.

以下是一些示例点:

testpts <- 
structure(list(x = c(4.9, 4.2, 4, 4.1, 4.4, 5.8, 5.8, 5.8, 5.8, 
5.5, 4.9, 3.2, 3.2, 3.3, 5.4, 5.4, 5.7, 6.4, 6.7, 6.7, 6, 4.8, 
3.6, 2.8, 3.5, 4.4, 5.1, 4, 3.7, 4.5, 4.9, 5.7), y = c(6.9, 6.2, 
5.3, 4.1, 3.1, 2.9, 2.9, 3.5, 4.2, 4.9, 5.1, 4.9, 4.9, 5.2, 6.9, 
6.9, 5.3, 3.8, 4.2, 5.6, 6.9, 5.8, 1.2, 2.5, 5.3, 6.4, 6.8, 7.6, 
6.9, 5.4, 4.8, 4.4)), .Names = c("x", "y"))
Run Code Online (Sandbox Code Playgroud)

设置基本情节

plot(NA,xlim=c(0,10),ylim=c(0,10))
points(testpts,pch=19)
chuld <- lapply(testpts,"[",chull(testpts))
polygon(chuld,lty=2,border="gray")
polygon(spline.poly(as.matrix(as.data.frame(chuld)),100),border="red",lwd=2)
Run Code Online (Sandbox Code Playgroud)

结果如下:

chullin'它了!

编辑添加一个凹凸的例子

这部分答案使用了alphahull

# load the required library
library(alphahull)

plot(NA,xlim=c(0,10),ylim=c(0,10))
points(testpts,pch=19)
# remove duplicate points so the ahull function doesn't error out
testptsnodup <- lapply(testpts,"[",which(!duplicated(as.matrix(as.data.frame(testpts)))))
Run Code Online (Sandbox Code Playgroud)

生成并绘制ahull对象 - 在确定多边形与数据的拟合时,alpha值似乎非常重要.

ahull.obj <- ahull(testptsnodup,alpha=2)
plot(ahull.obj,add=TRUE,col="red",wpoints=FALSE)
Run Code Online (Sandbox Code Playgroud)

结果如下:

在此输入图像描述


Ben*_*ker 8

ggalt软件包提供geom_encircle,这是应该提供这样的事情-凸,但平稳:

library(ggplot2)
library(ggalt)  ## v 0.4.0

df <- data.frame(x = rnorm(20), y = rnorm(20),
      z = sample(letters[1:5], 20, replace = TRUE))
ggplot(df, aes(x, y, colour = z)) + geom_point() +
     geom_encircle(aes(fill=z),alpha=0.3)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


ags*_*udy 3

经过一番谷歌搜索后,我稍微修改了这个例子Morota ggplot2

编辑

它使用带有贝塞尔曲线的chull函数

library(ggplot2)
library(plyr)
library(Hmisc)



df <- data.frame(x = rnorm(20), y = rnorm(20),z = sample(letters[1:5], 20, rep = T))
ggplot(df, aes(x, y, colour = z)) + geom_point()

find_hull <- function(df) {
    res.ch <- df[chull(df$x, df$y), ]
    res <- bezier(res.ch)
    res <- data.frame(x=res$x,y=res$y)
    res$z <- res$z
    res
  }
hulls <- ddply(df, "z", find_hull)
ggplot(df, aes(x, y, colour = z,fill = z)) +
  geom_point() + geom_polygon(data = hulls,alpha = 0.4)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述