I'm just trying to white-fill the area outside of a simple polygon. For some reason, it's screwing up by drawing a weird stake through the center like it thinks its a vampire slayer or something.
I tried following this post but something's gone bananas. I would've thought this would be easier, but it's proving to be quite an irascible little demon.
How do I white-fill the area outside a projection-friendly polygon without screwing up the area inside the polygon? thanx
# reproducible example
library(rgeos)
library(maptools)
shpct.tf <- tempfile() ; td <- tempdir()
download.file(
"ftp://ftp2.census.gov/geo/pvs/tiger2010st/09_Connecticut/09/tl_2010_09_state10.zip" ,
shpct.tf ,
mode = 'wb'
)
shpct.uz <- unzip( shpct.tf , exdir = td )
# read in connecticut
ct.shp <- readShapePoly( shpct.uz[ grep( 'shp$' , shpct.uz ) ] )
# box outside of connecticut
ct.shp.env <- gEnvelope( ct.shp )
# difference between connecticut and its box
ct.shp.diff <- gDifference( ct.shp.env , ct.shp )
# prepare both shapes for ggplot2
f.ct.shp <- fortify( ct.shp )
outside <- fortify( ct.shp.diff )
library(ggplot2)
# create all layers + projections
plot <- ggplot(data = f.ct.shp, aes(x = long, y = lat)) #start with the base-plot
layer1 <- geom_polygon(data=f.ct.shp, aes(x=long,y=lat), fill='black')
layer2 <- geom_polygon(data=outside, aes(x=long,y=lat), fill='white')
co <- coord_map( project = "merc" )
# this works
plot + layer1
# this does not
plot + layer1 + layer2
# this also does not
plot + layer1 + layer2 + co
ct.shp.diff
consists of four polygons:or
Therefore, you need a group aesthetic in
layer2
(otherwise ggplot tries to plot a single polygon, which results in weird connections between the parts):