I would like to draw SpatialPolygons from library sp with holes in ggplot2.
Thanks to others questions on stackoverflow, I know that this is allowed while dealing with clockwise written polygons:
http://stackoverflow.com/questions/12047643/geom-polygon-with-multiple-hole/12051278#12051278
Indeed, when transforming a SpatialPolygons using broom::tidy (replacing ggplot2::fortify), holes polygons are saved in clockwise direction to be drawn as holes.
In ggplot2, the way polygons with holes are drawn force to draw them once using fill, and another time using colour, otherwise you may see lines crossing polygons.
When dealing with multiple subpolygons, some with holes, this is more tricky, the order of points features as defined by broom::tidy may not allow for filling polygons (see image below).
Do any of you have a solution to get rid of this filling problem behaviour ?
Here is a reproducible example:
library(sp)
library(ggplot2)
# Create two polygons: second would be a hole inside the first
xy = cbind(
x = c(13.4, 13.4, 13.6, 13.6, 13.4),
y = c(48.9, 49, 49, 48.9, 48.9)
)
hole.xy <- cbind(
x = c(13.5, 13.5, 13.45, 13.45, 13.5),
y = c(48.98, 48.92, 48.92, 48.98, 48.98)
)
# Transform as SpatialPolygons with holes
xy.sp <- SpatialPolygons(list(
Polygons(list(Polygon(xy),
Polygon(hole.xy, hole = TRUE)), "1"),
Polygons(list(Polygon(xy + 0.2),
Polygon(xy + 0.35),
Polygon(hole.xy + 0.2, hole = TRUE)), "2")
))
# Transform SpatialObject to be used by ggplot2
xy.sp.l <- broom::tidy(xy.sp)
ggplot(xy.sp.l) +
geom_polygon(aes(x = long, y = lat, group = id, fill = id))

(source: statnmap.com)



