如何在R中的完整数据集上创建最小边界矩形

时间:2017-01-24 16:54:47

标签: r geospatial spatial ellipse

假设我有一组这样的坐标,例如:

m <- data.frame(replicate(2,sample(0:9,20,rep=TRUE)))

我想在所有点周围绘制一个框,以便创建一个最小边界矩形。

a <- bounding.box.xy(m)
plot(m)
par(new=T)
plot(a, main="Minimum bounding rectangle")

但是这个方框并没有解决所有问题。

我也有兴趣在这些点周围绘制标准偏差圆/椭圆,但我不知道这个功能。

enter image description here

1 个答案:

答案 0 :(得分:4)

<强> RECTANGLE

您可以获取最小和最大x和y的值,然后使用这些值绘制polygon。试试这个:

set.seed(42)
m <- data.frame(replicate(2,sample(0:9,20,rep=TRUE)))
lx = min(m$X1)
ux = max(m$X1)
ly = min(m$X2)
uy = max(m$X2)
plot(m)
title(main = "Minimum bounding rectangle")
polygon(x = c(lx, ux, ux, lx), y = c(ly, ly, uy, uy), lty = 2)

enter image description here

<强> POLYGON

有关围绕一组点绘制曲线的更多讨论可以找到here。一种方法是利用chull命令创建凸包。

首先导入以下功能

plot_boundary <- function(x,y,offset = 0,lty = 1,lwd = 1,border = "black",col = NA){
# 'offset' defines how much the convex hull should be bumped out (or in if negative value)
# relative to centroid of the points. Typically value of 0.1 works well 
BX = x + offset*(x-mean(x))
BY = y + offset*(y-mean(y))
k2 = chull(BX,BY)
polygon(BX[k2],BY[k2],lty = lty,lwd = lwd,border = border,col = col)
}

然后你可以生成数据并围绕它绘制边界。

set.seed(242)
m <- data.frame(replicate(2,sample(0:9,20,rep=TRUE)))
plot(m, xlim = c(0,10), ylim = c(0,10))
title(main = "Minimum bounding rectangle")
plot_boundary(x = m$X1, y = m$X2, lty = 2)

enter image description here

<强> ELLIPSE

set.seed(42)
A = data.frame(x = rnorm(20, 25, 4), y = rnorm(20, 11, 3))
B = data.frame(x = rnorm(20, 12, 5), y = rnorm(20, 5, 7))
plot(rbind(A,B), type = "n", ylim = c(-10,20), xlim = c(0,40), asp = 1)
require(ellipse)
red_eli = ellipse(cor(A$x,A$y), scale = c(sd(A$x), sd(A$y)),
                                centre = c(mean(A$x), mean(A$y)))
blue_eli = ellipse(cor(B$x,B$y), scale = c(sd(B$x), sd(B$y)),
                                centre = c(mean(B$x), mean(B$y)))
points(A, pch = 19, col = "red")
points(B, pch = 18, col = "blue")
lines(red_eli, col = "red")
lines(blue_eli, col = "blue", lty = 2)

enter image description here