4
votes

I have a shapefile (polygon) that I only want to plot part of, so using ggplot's geom_path I limit the visible path with xlim and ylim. Shapefile is available here (2.5 MB).

library(rgdal)
library(ggplot2)


coast <- readOGR(dsn=".", layer="coast-rgdal")
coast.df <- fortify(coast, region="STATE_NAME")
p <- ggplot(coast.df, aes(x=long, y=lat, group=group)) +
  geom_path(colour="black", size=1/4) +
  xlim(146, 148) + ylim(-39.25, -37.5) + coord_fixed()
p

Which looks like this:

Vic coast open

What I would like to have is something like this with a closed path (done with gimp):

Vic coast closed

Can I do that with ggplot commands? Or something else in R?

For reference, the full polygon looks like:

enter image description here

1

1 Answers

3
votes

You can use gIntersection from the rgeos package to extract this region:

library(rgdal)
library(ggplot2)
library(rgeos)

coast <- readOGR(dsn=".", layer="coast-rgdal")

lim <- cbind(c(146, 148, 148, 146, 146),
             c(-39.25, -39.25, -37.5, -37.5, -39.25))
x <- SpatialPolygons(list(Polygons(list(Polygon(lim)), ID="1")))
proj4string(x) <- proj4string(coast)
res <- gIntersection(coast, x)

coast.df <- fortify(res)
p <- ggplot(coast.df, aes(x=long, y=lat, group=group)) +
     geom_path(colour="black", size=1/4) +
     xlim(146, 148) + ylim(-39.25, -37.5) + coord_fixed()
p

R plot