This is almost an extension of a question asked on stackoverflow (https://stackoverflow.com/questions/12196440/extract-feature-coordinates-from-spatialpolygons-and-other-sp-classes), so I'll use the demo dataset from there.
I'm attempting to plot these polygons with lines(), so I can overlay these with an image.plot. To do this, I use fortify, like so
# taken from the linked stackoverflow question Sr1 = Polygon(cbind(c(2,4,4,1,2),c(2,3,5,4,2))) Sr2 = Polygon(cbind(c(5,4,2,5),c(2,3,2,2))) Sr3 = Polygon(cbind(c(4,4,5,10,4),c(5,3,2,5,5))) Sr4 = Polygon(cbind(c(5,6,6,5,5),c(4,4,3,3,4)), hole = TRUE) Srs1 = Polygons(list(Sr1), "s1") Srs2 = Polygons(list(Sr2), "s2") Srs3 = Polygons(list(Sr3, Sr4), "s3/4") SpP = SpatialPolygons(list(Srs1,Srs2,Srs3), 1:3) image.plot(x = c(0:10), y = c(0:10), z = matrix(runif(100, 0,1), nrow = 10), col = terrain.colors(20)) # fake data so lines() plays nice. lines(fortify(SpP)) # there's a weird line connecting the square island in the middle to the polygon surrounding it
What I would like to get is an image like this, which I can produce with ggplot...
require(ggplot2) ggplot(aes(x = long, y = lat, group = group), data = fortify(SpP)) + geom_path()
I can see two possible solutions to this, either an analog to the "group =" argument in the aes() call in ggplot(), or some way to get fortify to insert 'NA' between different groups (this is what the lines() function interprets as breaks). I can produce an effect manually, but I couldn't do this with the real dataset.
SpP3 <- rbind(SpP2[1:5,], rep(NA, 7), SpP2[6:10,], rep(NA, 7), SpP2[10:14,], rep(NA, 7), SpP2[15:19,]) image.plot(x = c(0:10), y = c(0:10), z = matrix(runif(100, 0,1), nrow = 10), col = terrain.colors(20)) lines(SpP3)
edit: I'd like to be able to produce these plots using image.plot, since it's faster for my real dataset, and I will be more compatible with what others I'm working with are using.