我认为您想要数据的凸包。尝试这个
library(grDevices) # load grDevices package
df <- data.frame(X = c(-62, -40, 9, 13, 26, 27, 27),
Y = c( 7, -14, 10, 9, -8, -16, 12)) # store X,Y together
con.hull.pos <- chull(df) # find positions of convex hull
con.hull <- rbind(df[con.hull.pos,],df[con.hull.pos[1],]) # get coordinates for convex hull
plot(Y ~ X, data = df) # plot data
lines(con.hull) # add lines for convex hull
编辑
如果您想从原点添加一条线到凸包的每一侧,使得每条线都垂直于凸包,请尝试以下操作:
getPerpPoints <- function(mat) {
# mat: 2x2 matrix with first row corresponding to first point
# on the line and second row corresponding to second
# point on the line
#
# output: two points which define the line going from the side
# to the origin
# store the inputs more conveniently
x <- mat[,1]
y <- mat[,2]
# define a new matrix to hold the output
out <- matrix(0, nrow = 2, ncol = 2)
# handle special case of vertical line
if(diff(x) == 0) {
xnew <- x[1]
}
else {
# find point on original line
xnew <- (diff(y) / diff(x)) * x[1] - y[1]
xnew <- xnew / (diff(y) / diff(x) + diff(x) / diff(y))
}
ynew <- -(diff(x) / diff(y)) * xnew
# put new point in second row of matrix
out[2,] <- c(xnew, ynew)
return(out = out)
}
绘制初始点以及数据的凸包后,运行上面的代码和以下代码:
for(i in 1:4) {
lines(getPerpPoints(con.hull[i:(i+1),]))
}
请记住,从原点到每一侧的一些线不会在数据凸包的内部终止。这是我得到的输出:
