如何使用ggplot2剪切或裁剪或白色填充围绕多边形外部的矩形

时间:2014-10-14 07:16:14

标签: r map ggplot2 gis map-projections

我只想尝试填充简单多边形之外的区域。出于某种原因,通过在中心画一个奇怪的赌注,就像它认为它是一个吸血鬼杀手或其他东西一样搞砸了。

我尝试跟随this post,但有些东西已经过香蕉了。我以为这会更容易,但事实证明这是一个非常暴躁的小恶魔。

如何在投影友好多边形外部填充区域而不拧紧多边形内部 区域?感谢名单

# 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

enter image description here

1 个答案:

答案 0 :(得分:4)

ct.shp.diff由四个多边形组成:

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

R> nlevels(outside$group) 
# 4

因此,您需要layer2中的群体审美(否则ggplot会尝试绘制单个多边形,这会导致各个部分之间出现奇怪的连接):

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

plot