How can I plot shapefile loaded through fastshp in ggplot2?
Asked Answered
B

1

4

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?

Binford answered 24/4, 2012 at 22:17 Comment(0)
S
4

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()
Sunil answered 25/4, 2012 at 0:27 Comment(5)
@otsaw: I've added an alternate approach that will render holes correctlySunil
@JimM. this is a great solution but unfortunately no longer works. Is there an alternative workflow to obtain the correctly formatted data.frame? Just posted: #59741503Regurgitation
@CyrusMohammadian: Nowadays, I would probably go with the sf package (i.e. read shapefiles via st_read), which can be plotted with ggplot with geom_sf : cran.r-project.org/web/packages/sf/vignettes/sf5.html#ggplot2Sunil
@JimM. Yep, my go to for years was rgdal and more recently sf given as you mentioned the geom_sf in ggplot2 but I currently lack access to installing non-R dependencies and needed a solution that didn't rely on gdal or C libraries used by sfRegurgitation
@JimM. checkout #59741503 for a solution if you're interested!Regurgitation

© 2022 - 2024 — McMap. All rights reserved.