2017-05-23 1 views
1

Ich möchte eine SpatialPolygonsDataFrame mit der Ausgabe von get_map in ggplot2 machen. Ich habe nach etwas Versuch und Irrtum einen Weg gefunden, es zu tun, aber es scheint mir verworren. Gibt es einen saubereren Weg?Gehe von map_data zu SpatialPolygonsDataFrame

library(ggplot2) 
library(sp) 
library(plyr) 
pnw.df <- map_data("state",region=c("washington","oregon","idaho")) 
# delete islands from subregions 
pnw.df$subregion[is.na(pnw.df$subregion)] <- "main" 
pnw.df <- subset(pnw.df,subregion == "main") 

getPolygons <- function(x) { 
    Polygons(list(Polygon(x[,c("long","lat")])),ID=unique(x$region)) 
} 

pnw.sp <- SpatialPolygons(dlply(pnw.df, .(region), getPolygons)) 
pnw.sp <- as(pnw.sp,"SpatialPolygonsDataFrame") 
proj4string(pnw.sp) <- "+proj=longlat +ellps=WGS84" 
plot(pnw.sp) 

Antwort

0

Schauen Sie in maptools::map2SpatialPolygons, versuchen Sie es mit seinen Beispielen. map_data liest die Daten von maps und legt sie in eine data.frame, was nicht sehr hilfreich ist. Die Funktion maptools nimmt dieselben Daten von maps und konvertiert sie in ein SpatialPolygons Objekt.

Verwandte Themen