Description
I have a SpatialPolygonsDataFrame in which the FIDs have been set to a specific column in the data.frame.
fortify.SpatialPolygonsDataFrame is then not giving the result I expected; it seems to be reordering the features and
giving them the wrong label; the 'id' column of the resulting ggplot data.frame doesn't match the region id of the original sp object.
The reordering seems to happen in the split() or invert() commands of fortify.SpatialPolygonsDataFrame().
I have attached reproducible code, with the expected spplot() results, the unexpected results from fortify.SpatialPolygonsDataFrame(), and
how I fixed it by rewriting the fortify to be more like fortify.SpatialPolygons(), and using the Feature IDs to name the ids and merge the data.frame attributes.
It is entirely possible that I am using the region parameter of fortify() improperly, I don't know.
Does anyone know what is going wrong with fortify.SpatialPolygonsDataFrame() here, or with how I am using it?
Nicholas
Nicholas Nagle,
Dept. of Geography
University of Tennessee
307 Burchfiel Geography Bldg.
Knoxville, TN 37996
#################################################################
download.file('http://graunt.bus.utk.edu/Files/boston_shp.Rdata','boston_shp.Rdata')
load('boston_shp.Rdata')
# boston_shp: the Harrison-Rubinfeld boston data, attached to the 1970 tract boundaries
# from the National Historical GIS <http://www.nhgis.org>
# The Feature IDs are also the 'TRACT' columns
# Desired result...
spplot(boston_shp,'dis')
####################
# Does not work as expected
boston.ggdf <- fortify(boston_shp,region='TRACT')
# Merge the ggplot data frame with the attributes attributes, matching
# boston.ggdf$id to row.names(boston_shp@data)
boston.ggdf <- cbind(boston.ggdf, boston_shp@data[as.character(boston.ggdf$id),])
boston.ggplot <- ggplot(boston.ggdf, aes(x=long, y=lat, group=group, fill=dis))
boston.ggplot+geom_polygon()+coord_equal()
########################################
# This does work as expected
saferFortify.SPDF <- function(model, data, region=NULL){
warning('Using FIDs as the id. User should verify that Feature IDs are also the row.names of data.frame. See spChFIDs().')
attr <- as.data.frame(model)
coords <- ldply(model@polygons,fortify)
coords <- cbind(coords,attr[as.character(coords$id),])
}
boston.ggdf <- saferFortify.SPDF(boston_shp)
boston.ggplot <- ggplot(boston.ggdf, aes(x=long, y=lat, group=group, fill=dis))
boston.ggplot+geom_polygon()+coord_equal()