In R, how can I convert SpatialPolygons* to map ob

2019-06-25 12:13发布

问题:

I'm trying to make use of ProportionalSymbolMap map as defined in this JSS paper.

In order to plot proportional symbols I first need an object of map class.

The methods I normally use however return SpatialPolygonDataFrame. Is there any package or method that could be of help here?

回答1:

Hack is the way to go about it. I just used this set of commands to take apart a SpatialPolygons* object and put it back together again as an object of class map. I hope you like it:

# read in shapefile as normal SpatialPolygons
xx <- readShapePoly(system.file("shapes/sids.shp", package="maptools")[1], IDvar="FIPSNO", proj4string=CRS("+proj=longlat +ellps=clrk66"))

# Formatting the data
require(reshape)
# Identifier column to split data on
xx@data$id <- rownames(xx@data)

# Convert to dataframe
xx.df <- as.data.frame(xx)

#Fortfy automagic
xx.fort <- fortify(xx, region="id")

# Join operation - one row per coordinate vector
xx <- join(xx.fort, xx.df,by="id")

# Split by ID because we need to add NA at end of each set of polygon coordinates to 'break' the line
xxSp <- split(xx, xx$id)

# Need to insert NA at end of each polygon shape to cut off that shape
xxL <- do.call( rbind , (lapply( xxSp , function(x) { j <- x[ nrow(x) , ] ; j[1:2] <- c(NA,NA); rbind( x , j ) })) )


# Create list object with same structure as map object
xxMap <- list( x = xxL$long , y = xxL$lat , range = c( range(xxL$long) , range(xxL$lat) ) , names = as.character(unique( xxL$NAME ) ) )

# Define as a map class object
attr(xxMap , "class") <- "map"

# Plot!!
map( xxMap )