how to snip or crop or white-fill a rectangle tigh

2019-07-02 22:14发布

问题:

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

回答1:

ct.shp.diff consists of four polygons:

R> length(ct.shp.diff@polygons[[1]]@Polygons)
# 4

or

R> nlevels(outside$group) 
# 4

Therefore, you need a group aesthetic in layer2 (otherwise ggplot tries to plot a single polygon, which results in weird connections between the parts):

layer2 <- geom_polygon(data=outside, aes(x=long, y=lat, group=group), fill='white')
plot + layer1 + layer2 + co