How can I plot shapefile loaded through fastshp in ggplot2?

 ̄綄美尐妖づ 提交于 2019-12-07 17:27:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!