看代码:
library(sf);library(dplyr);library(ggplot2);library(smoothr)
### 示例数据准备
dat_cloud <- as.data.frame(alphahull::rkoch(2e3,side = 1,niter = 3)) %>%
dplyr::rename("x"=1,"y"=2) %>% mutate(y = y -0.25) %>%
mutate(lable = ifelse(y > 0,"a","b")) %>%
st_as_sf(coords = c("x","y"))
dat_grid <- expand.grid(x = seq(-1,1,.1),y = seq(-1,1,.1)) %>%
st_as_sf(coords = c("x","y"))
### 根据标签分组识别点集的轮廓
hll_group <- dat_cloud %>% group_by(lable) %>% summarise() %>%
st_concave_hull(ratio = .25,allow_holes = F) %>%
st_simplify(dTolerance = 0.01) %>%
smooth(method = "chaikin")
### 识别点集轮廓
hull <- st_concave_hull(st_union(dat_cloud),ratio = .2,allow_holes = F) ### 在windows上使用该函数依赖 R4.3 和 Rtools43 上集成的 GEOS 3.11 库
### 平滑轮廓曲线
hull_smooth <- smooth(hull,method = "chaikin")
### 以几何中心为标点等比例放大集合图形
enlarge_hull <- (hull - st_centroid(hull)) * .75 + st_centroid(hull)
### 为几何图形添加缓冲边界
buf <- st_buffer(hull,dist = .15,singleSide = T,nQuadSegs = 2)
### 提取被几何图形包裹的点
sampe_in_polygon <- dat_grid[st_contains(buf,dat_grid)[[1]],]
### 提取位于点集边缘上的点,依赖与计算点集的轮廓
boundary_pts <- st_intersection(st_boundary(hull),dat_cloud)
### 提取包围点集的最小矩形
bbox <- st_bbox(st_union(dat_cloud)) %>% st_as_sfc()
### 估计几何图形的面积
st_area(hull_smooth) ### 计算多边形面积
st_area(bbox)
ggplot() +
geom_sf(data = dat_grid, alpha = .5 ,color = "orange") +
geom_sf(data = dat_cloud,size = .1,color = "grey") +
geom_sf(data = st_centroid(st_union(dat_cloud)),color = "red") +
# geom_sf(data = hull,fill = NA,color = "blue",linewidth = .4) +
geom_sf(data = hull_smooth,fill = NA,color = "red") +
geom_sf(data = buf,color = "black",fill = NA) +
geom_sf(data = enlarge_hull,fill = NA, color = "green",linewidth = .5) +
geom_sf(data = sampe_in_polygon,color = "grey20") +
geom_sf(data = bbox,fill = NA ,color = "red",linewidth = .7) +
geom_sf(data = boundary_pts,color= "red") +
geom_sf(data = hll_group,aes(fill = lable),alpha = .75)
sf 指南
3. Manipulating Simple Feature Geometries • sf (r-spatial.github.io)
Geometric unary operations on simple feature geometry sets — geos_unary • sf (r-spatial.github.io)
Simplifying geospatial features in R with sf and rmapshaper | R-bloggers
Experiments with sf (spatial data in r) (rstudio-pubs-static.s3.amazonaws.com)
smoothr 指南
smoothr: Smooth and Tidy Spatial Features in R (r-project.org)
网友评论