我有一个横断面线的多边形对象,我想将其分成3个相等的部分,这些部分沿着横断面线是一个接一个的。到目前为止,我只能垂直分割多边形,这会导致部分不连续。
以下是使用哈佛森林数据的可复制示例,可通过以下link
获得下载并解压缩数据后,您将看到一个名为HARV的文件夹。该文件夹中有shapefile HARV_roads.shp
导入HARV_roads.shp
lines_HARV <- readOGR("/Your file path/NEON-DS-Site-Layout-Files/HARV/HARV_roads.shp")
仅获取行人路线
footpath_HARV <- lines_HARV[lines_HARV$TYPE == "footpath",]
绘制行人路
plot(footpath_HARV,
lwd=6,
main="NEON Harvard Forest Field Site\n Footpath")
使用缓冲区从人行道线创建较粗的多边形对象,以模拟X宽度的横断面线
require(raster)
footpath_buffer <- buffer(footpath_HARV,width=40)
绘制footpath_buffer
plot(footpath_buffer)
使用post中的Barry Rowlingson的代码(如下)将缓冲区分成3个相等的部分:
makeVchopper <- function(pol){
bb = bbox(pol)
delta = (bb[2,2] - bb[2,1])/10
xmin = bb[1,1]-delta
ymin = bb[2,1]-delta
ymax = bb[2,2]+delta
choppoly = function(xmax){
readWKT(sprintf("POLYGON((%s %s, %s %s, %s %s, %s %s, %s %s))",
xmin,ymin, xmin,ymax, xmax,ymax, xmax,ymin,
xmin,ymin))
}
choppoly
}
slicer <- function(pol, xmin, xmax){
bb = bbox(pol)
delta = (bb[2,2] - bb[2,1])/10
ymax = bb[2,2] + delta
ymin = bb[2,1] - delta
r = readWKT(sprintf("POLYGON((%s %s, %s %s, %s %s, %s %s, %s %s))",
xmin,ymin, xmin,ymax, xmax,ymax, xmax,ymin, xmin,ymin))
gIntersection(pol,r)
}
chop_thirds <- function(pol, fractions=c(1/3, 2/3)){
chopper = makeVchopper(pol)
bb = bbox(pol)
xmin = bb[1,1]
xmax = bb[1,2]
totalArea = gArea(pol)
chopped_area = function(x){
gArea(gIntersection(chopper(x),pol))
}
edges = lapply(fractions, function(fraction){
target = totalArea * fraction
target_function = function(x){
chopped_area(x) - target
}
uniroot(target_function, lower=xmin, upper=xmax)$root
})
xdelta = (xmax-xmin)/10
chops = matrix(c(xmin-xdelta, rep(edges,rep(2,length(edges))),
xmax+xdelta), ncol=2, byrow=TRUE)
apply(chops, 1, function(edges){
slicer(pol, edges[1], edges[2])
})
}
将footpath_buffer分为3个相等的部分:
parts.footpath <- chop_thirds(footpath_buffer)
绘制footpath_buffer和3个相等的部分
plot(footpath_buffer)
plot(parts.footpath[[1]], add=TRUE, col=1,border=F)
plot(parts.footpath[[2]], add=TRUE, col=2,border=F)
plot(parts.footpath[[3]], add=TRUE, col=3,border=F)
footpath_buffer现在分为3个相等的部分,但是这些部分被分解了。我希望达到这样的效果,其中每个部分沿着样条线都是连续的: