ggvoronoi
has a feature to bound the generated cells in a specified region:
mydf <- data.frame("x_coords"=c(17,51,28,34,12), "y_coords"=c(5,19,21,6,50))
vor_spdf <- voronoi_polygon(data=mydf ,x="x_coords",y="y_coords")
vor_df <- fortify_voronoi(vor_spdf)
rect = data.frame(x=c(14,32,32,14,14), y=c(7,7,27,27,7))
vor_spdf2 <- voronoi_polygon(data=mydf ,x="x_coords",y="y_coords", outline=rect)
vor_df2 <- fortify_voronoi(vor_spdf2)
Then you can get the are of these cropped cells using sf
(see this for more details):
mp_sf <- st_as_sf(vor_spdf2)
p_sf <- st_cast(mp_sf, "POLYGON")
area <- st_area(p_sf)
, and to plot them:
ggplot() +
geom_path(data=vor_df, aes(x=x,y=y,group=group))+
geom_polygon(data=vor_df2, aes(x=x, y=y,group=group,fill=id))+
geom_path(data=rect, aes(x=x, y=y))+
geom_point(data=mydf, aes(x=x_coords,y=y_coords))+
geom_text(data=vor_spdf2@data, aes(x=x_coords, y=y_coords, label=area), nudge_y = -2)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…