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 个解决方案
#1
4
ct.shp.diff
consists of four polygons:
ct.shp。diff由四个多边形组成:
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中需要一个群体审美观(否则,ggplot试图绘制单个多边形,从而导致各部分之间的怪异连接):
layer2 <- geom_polygon(data=outside, aes(x=long, y=lat, group=group), fill='white')
plot + layer1 + layer2 + co
#1
4
ct.shp.diff
consists of four polygons:
ct.shp。diff由四个多边形组成:
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中需要一个群体审美观(否则,ggplot试图绘制单个多边形,从而导致各部分之间的怪异连接):
layer2 <- geom_polygon(data=outside, aes(x=long, y=lat, group=group), fill='white')
plot + layer1 + layer2 + co