-->

How can I draw the polygons of a Voronoi Tesselati

2019-07-20 14:49发布

问题:

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)))