2

I have a set of lat and lon points I managed to plot a voronoi diagram with.

I would like to overlay the voronoi diagram on a shapefile of Singapore and delimit the voronoi diagram with the boundaries of the map.

The voronoi diagram I have is:

coords <- data.frame(Lat=c(1.29370,1.37640,1.25600,1.38370,1.38240,1.31910),Long=c(103.8125,103.8492,103.6790,103.8860,103.7603,103.8191))

library(deldir)
library(ggplot2)

#This creates the voronoi line segments
voronoi <- deldir(coords$Long, coords$Lat)

#Now we can make a plot

ggplot(data=coords, aes(x=Long,y=Lat)) +
  #Plot the voronoi lines
  geom_segment(
    aes(x = x1, y = y1, xend = x2, yend = y2),
    size = 2,
    data = voronoi$dirsgs,
    linetype = 1,
    color= "#FFB958") + 
  #Plot the points
  geom_point(
    fill=rgb(70,130,180,255,maxColorValue=255),
    pch=21,
    size = 4,
    color="#333333")

The map I have is:

library(raster)
sg <- getData(country="SGP", level=0) 

How do I plot the voronoi diagram on the map and delimit it by the boundaries of the map?

jsong005
  • 17
  • 3

2 Answers2

4

You can use dismo::voronoi followed by raster::intersect

library(dismo)
library(rgeos)

coords <- data.frame(Lat=c(1.29370,1.37640,1.25600,1.38370,1.38240,1.31910),Long=c(103.8125,103.8492,103.6790,103.8860,103.7603,103.8191))
sg <- getData(country="SGP", level=0) 

Create Voronoi diagram

v <- voronoi(coords[, c('Long', 'Lat')], ext=extent(sg)+.1)

Intersect with polygons

sgv <- v * sg
# or # sgv <- instersect(v, sg)

For plotting

plot(sgv)

Or

g <- gmap(sg, lonlat=TRUE, scale=2)
plot(g, interpolate=TRUE)
lines(sgv, col='red')
Robert Hijmans
  • 40,301
  • 4
  • 55
  • 63
  • On Linux, before running `install.packages("rgeos")` in `R`, I had to run the following as root: `apt install libgeos-dev` Source: https://stackoverflow.com/questions/38924767/error-installing-r-package-for-linux – Adam Smith Jun 23 '18 at 20:55
0

Maybe this will give you some ideas:

library(deldir)
library(ggplot2)
library (ggmap)

coords <- data.frame(
    lat=c(1.29370, 1.37640, 1.25600, 1.38370, 1.38240, 1.31910),
    lon=c(103.8125, 103.8492, 103.6790, 103.8860, 103.7603, 103.8191)
    )

voronoi <- deldir(coords$lon, coords$lat)

singapore.map <- get_map("singapore", zoom=11)

ggmap(singapore.map, extent = "normal")+
  geom_segment(
    aes(x=x1, y=y1, xend=x2, yend=y2),
    size=2,
    data=voronoi$dirsgs,
    linetype=1,
    color= "#FFB958")+ 
  geom_point(
    fill=rgb(70, 130, 180, 255, maxColorValue=255),
    pch=21,
    size=4,
    color="#333333")
Adam Smith
  • 2,584
  • 2
  • 20
  • 34