Skip to content
Prev 174431 / 398503 Next

Retrieving Vertices Coordinates from SpatialPolygons

This came up on R-sig-geo two days ago and this is what I said:

I have the following code in ggplot2 for turning a SpatialPolygon into
a regular data frame of coordinates.  You'll need to load ggplot2, and
then run fortify(yoursp).

fortify.SpatialPolygonsDataFrame <- function(shape, region = NULL) {
 attr <- as.data.frame(shape)
 # If not specified, split into regions based on first variable in attributes
 if (is.null(region)) {
   region <- names(attr)[1]
   message("Using ", region, " to define regions.")
 }

 # Figure out how polygons should be split up into the region of interest
 polys <- split(as.numeric(row.names(attr)), attr[, region])
 cp <- polygons(shape)

 # Union together all polygons that make up a region
 try_require(c("gpclib", "maptools"))
 unioned <- unionSpatialPolygons(cp, invert(polys))

 coords <- fortify(unioned)
 coords$order <- 1:nrow(coords)
 coords
}

fortify.SpatialPolygons <- function(model, data, ...) {
 ldply(model at polygons, fortify)
}

fortify.Polygons <- function(model, data, ...) {
 subpolys <- model at Polygons
 pieces <- ldply(seq_along(subpolys), function(i) {
   df <- fortify(subpolys[[model at plotOrder[i]]])
   df$piece <- i
   df
 })

 within(pieces,{
   order <- 1:nrow(pieces)
   id <- model at ID
   piece <- factor(piece)
   group <- interaction(id, piece)
 })
}

fortify.Polygon <- function(model, data, ...) {
 df <- as.data.frame(model at coords)
 names(df) <- c("long", "lat")
 df$order <- 1:nrow(df)
 df$hole <- model at hole
 df
}

fortify.SpatialLinesDataFrame <- function(model, data, ...) {
 ldply(model at lines, fortify)
}

fortify.Lines <- function(model, data, ...) {
 lines <- model at Lines
 pieces <- ldply(seq_along(lines), function(i) {
   df <- fortify(lines[[i]])
   df$piece <- i
   df
 })

 within(pieces,{
   order <- 1:nrow(pieces)
   id <- model at ID
   piece <- factor(piece)
   group <- interaction(id, piece)
 })
}

fortify.Line <- function(model, data, ...) {
 df <- as.data.frame(model at coords)
 names(df) <- c("long", "lat")
 df$order <- 1:nrow(df)
 df
}


Hadley
On Sat, Mar 21, 2009 at 7:33 AM, Enrico R. Crema <e.crema at ucl.ac.uk> wrote: