问题
I stumbled upon fastshp library and according to description (and my quick cursory tests) it really does offer improvements in time of reading large shapefiles compared to three other methods.
I'm using read.shp
function to load exemplary dataset from maptools package:
library("maptools")
setwd(system.file("shapes", package="maptools"))
shp <- read.shp("columbus.shp", format="polygon")
I chose 'polygon' format since accordng to docs:
This is typically the preferred format for plotting.
My question is how can I plot these polygons using ggplot2 package?
回答1:
Since read.shp
in the fastshp
package returns the polygon data in the form of a list of lists, it is then a matter of reducing it to a single dataframe required for plotting in ggplot2
.
library(fastshp)
library(ggplot2)
setwd(system.file("shapes", package="maptools"))
shp <- read.shp("columbus.shp", format="polygon")
shp.list <- sapply(shp, FUN = function(x) do.call(cbind, x[c("id","x","y")]))
shp.df <- as.data.frame(do.call(rbind, shp.list))
shp.gg <- ggplot(shp.df, aes(x = x, y=y, group = id))+geom_polygon()
EDIT: Based on @otsaw's comment regarding polygon holes, the following solution requires a couple of more steps but ensures that the holes are plotted last. It takes advantage that shp.df$hole is logical and polygons with hole==TRUE will be plotted last.
shp.list <- sapply(shp, FUN = function(x) Polygon(cbind(lon = x$x, lat = x$y)))
shp.poly <- Polygons(shp.list, "area")
shp.df <- fortify(shp.poly, region = "area")
shp.gg <- ggplot(shp.df, aes(x = long, y=lat, group = piece, order = hole))+geom_polygon()
来源:https://stackoverflow.com/questions/10306831/how-can-i-plot-shapefile-loaded-through-fastshp-in-ggplot2