How can I draw the polygons of a Voronoi Tesselation instead of the segments?

六眼飞鱼酱① 提交于 2019-12-12 17:16:33

问题


I've found a method to draw the segments of a Voronoi tesselation using ggplot2 :

library(deldir)
library(ggplot2)
library(ggthemes)
set.seed(123)
df <- data.frame(lat = rnorm(20,39,10),long = rnorm(20,-98,15))
voronoi <- deldir(df$long, df$lat)

ggplot(data=df, aes(x=long,y=lat)) +
  geom_segment(aes(x = x1, y = y1, xend = x2, yend = y2),size = 2,data = voronoi$dirsgs,linetype = 1,color= "#419AB0") +
  geom_point(fill="#EACA3E",pch=21,size = 4,color="white") 

I would like to know if it is possible to draw polygons intead of segments but I don't know how to create a dataset with the contour of each polygon.


回答1:


Here's a simple way to convert the line segments to SpatialPolygons objects.

library(rgeos)

## Convert data.frame of segment coordinates to a list of SpatialLines objects
ll <- apply(voronoi$dirsgs, 1, FUN=function(X) {
    readWKT(sprintf("LINESTRING(%s %s, %s %s)", X[1], X[2], X[3], X[4]))
})

## Convert SpatialLines list to SpatialPolygons object
pp <- gPolygonize(ll)

## Plot to check that it works    
set.seed=11
plot(pp, col=sample(colors(), length(pp)))



来源:https://stackoverflow.com/questions/24311304/how-can-i-draw-the-polygons-of-a-voronoi-tesselation-instead-of-the-segments

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!