r - 如何使用 ggplot2 剪切、裁剪或白色填充紧紧包围多边形外部的矩形

标签 r dictionary ggplot2 gis map-projections

我只是想用白色填充简单多边形之外的区域。由于某种原因,它在中心画了一根奇怪的木桩,就像它认为自己是吸血鬼 killer 或其他什么东西一样,搞砸了。

我尝试关注this post但有些事情已经变得疯狂了。我本以为这会更容易,但事实证明它是一个相当暴躁的小恶魔。

如何对适合投影的多边形外部区域进行白色填充,而不破坏多边形内部的区域?感谢x

# 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

最佳答案

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

关于r - 如何使用 ggplot2 剪切、裁剪或白色填充紧紧包围多边形外部的矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26354768/

相关文章:

r - DBSCAN 用于按位置和密度对数据进行聚类

通过 qsub 运行 R 脚本

java - 从 <String, Object> 转换为 <String, String> 时无法从 map 获取所有记录

r - ggplot2 离散比例的连续颜色并删除图例

r - 避免标签与直接标签和 ggplot2 重叠

r - 如何使用ggplot2创建一维图表?

r - 全局环境变量内存使用表

r - SparkR foreach 循环

Python 字典多值

haskell - 表示短位串的最佳方式是什么?