R 从多边形中删除相交点
我试图从两个R 从多边形中删除相交点,r,clip,polygons,sp,R,Clip,Polygons,Sp,我试图从两个sp几何体的gDifference创建一组新的SpatialPoints。假设如下: 您有两个空间多边形: library(rgeos) library(sp) #Create SpatialPlygons objects polygon1 <- readWKT("POLYGON((-190 -50, -200 -10, -110 20, -190 -50))") #polygon 1 polygon2 <- readWKT("POLYGON((-1
sp
几何体的gDifference
创建一组新的SpatialPoints
。假设如下:
您有两个空间多边形
:
library(rgeos)
library(sp)
#Create SpatialPlygons objects
polygon1 <- readWKT("POLYGON((-190 -50, -200 -10, -110 20, -190 -50))")
#polygon 1
polygon2 <- readWKT("POLYGON((-180 -20, -140 55, 10 0, -140 -60, -180 -20))") #polygon 2
#Plot both polygons
par(mfrow = c(1,2)) #in separate windows
plot(polygon1, main = "Polygon1") #window 1
plot(polygon2, main = "Polygon2") #window 2
如何获得仅具有polygon2
非相交点的sp
几何体(即下图中的红色点)
提前谢谢 我认为通过比较
clip
和polygon2
的坐标,可以得出不相交点
library(ggplot2) # as @shayaa commented, ggplot2::fortify is useful.
clip_coords <- fortify(clip)[,1:2] # or, clip@polygons[[1]]@Polygons[[1]]@coords
polygon2_coords <- fortify(polygon2)[,1:2] # or, polygon2@polygons[[1]]@Polygons[[1]]@coords
duplicated_coords <- merge(clip_coords, polygon2_coords)
# duplicated_coords is the non-intersecting points of the polygon2
res <- SpatialPoints(duplicated_coords)
plot(clip)
plot(res, col="red", pch=19, add=T)
library(ggplot2)#正如@shayaa所评论的,ggplot2::fortify很有用。
剪辑坐标将它们转换为单独的线,测试交叉点,然后选择不相交的线?我已经尝试过了,但是返回了整个polygon2
。我假设它只考虑交叉点,当整个行被“包含”之后,你需要确定产生期望多边形的顺序。调整顺序后,ggplot2::fortify
函数将提供一个很好的data.frame用于绘图。我使用了tidy
而不是fortify
,结果仍然相同。我一直在尝试使用相同的代码来获取gIntersection
而不是gDifference
,但是得到的sp
对象是clip,而不是多边形的空间点<代码>合并(clip\u-coords,polygons2\u-coords,all.x=T)
不起作用。好的,我编辑了。这就是你所希望的答案吗?
library(ggplot2) # as @shayaa commented, ggplot2::fortify is useful.
clip_coords <- fortify(clip)[,1:2] # or, clip@polygons[[1]]@Polygons[[1]]@coords
polygon2_coords <- fortify(polygon2)[,1:2] # or, polygon2@polygons[[1]]@Polygons[[1]]@coords
duplicated_coords <- merge(clip_coords, polygon2_coords)
# duplicated_coords is the non-intersecting points of the polygon2
res <- SpatialPoints(duplicated_coords)
plot(clip)
plot(res, col="red", pch=19, add=T)
## an independent method
library(ggplot2); library(dplyr)
clip2 <- gIntersection(polygon2, polygon1, byid = TRUE, drop_lower_td = T)
res2.1 <- fortify(clip2)[,1:2] %>% setdiff(polygon2_coords) %>% # not_duplicated_coords
SpatialPoints()
## a method usign a gDifference.sp.coords
res2.2 <- fortify(clip2)[,1:2] %>% merge(clip_coords) %>%
distinct() %>% SpatialPoints() # res2.2 is equal to res2.1 in elements.
plot(polygon_set, main = "Polygon1 & Polygon2")
plot(clip2, col="red", add=T)
plot(res2.1, col="blue", pch=19, add=T)