Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
738 views
in Technique[技术] by (71.8m points)

geometry - How do I find the area of voronoi cells within a given region in R?

Say I have the following data:

mydf <- data.frame("x_coords"=c(17,51,28,34,12), "y_coords"=c(5,19,21,6,50))

I want to create a voronoi diagram from these data points, and furthermore retrieve coordinate information about each cell. From the ggvoronoi package on CRAN, I call the following functions:

vor_spdf <- voronoi_polygon(data=mydf ,x="x_coords",y="y_coords")
vor_df <- fortify_voronoi(vor_spdf)

Now, vor_df provides me with the coordinates bounding the areas of each cell. In the image of the voronoi plot below, say I wanted to find the area each voronoi cell contributes to the region encapsulated within the red rectangle. enter image description here

In summary, I want to find the areas of the regions I've denoted as 1, 2, and 3. How would I go about doing this in R?

question from:https://stackoverflow.com/questions/66049239/how-do-i-find-the-area-of-voronoi-cells-within-a-given-region-in-r

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...