Skip to content
Prev 5301 / 29559 Next

Extract coordinates from SpatialPolygonsDataFrame

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 Thu, Mar 19, 2009 at 4:37 PM, Torleif Markussen Lunde
<torleif.lunde at cih.uib.no> wrote: