【发布时间】:2014-10-14 11:38:24
【问题描述】:
这个问题是我prior SO question的后续问题,与this question有关。
我只是想用 ggplot2 填充比简单多边形大 10% 的区域。也许我把事情分组错了?这是尖峰的照片,下面有可重现的代码
# reproducible example
library(rgeos)
library(maptools)
library(raster)
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 )
ct.shp.out <- as( 1.2 * extent( ct.shp ), "SpatialPolygons" )
# difference between connecticut and its box
ct.shp.env.diff <- gDifference( ct.shp.env , ct.shp )
ct.shp.out.diff <- gDifference( ct.shp.out , ct.shp )
library(ggplot2)
# prepare both shapes for ggplot2
f.ct.shp <- fortify( ct.shp )
env <- fortify( ct.shp.env.diff )
outside <- fortify( ct.shp.out.diff )
# 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=env, aes(x=long,y=lat,group=group), fill='white')
layer3 <- geom_polygon(data=outside, aes(x=long,y=lat,group=id), fill='white')
co <- coord_map( project = "albers" , lat0 = 40.9836 , lat1 = 42.05014 )
# this works
plot + layer1
# this works
plot + layer2
# this works
plot + layer1 + layer2
# this works
plot + layer2 + co
# this works
plot + layer1 + layer3
# here's the problem: this breaks
plot + layer3 + co
# this also breaks, but it's ultimately how i want to display things
plot + layer1 + layer3 + co
# this looks okay in this example but
# does not work for what i'm trying to do-
# cover up points outside of the state
plot + layer3 + layer1 + co
【问题讨论】:
-
来自
coord_map函数的文档:“这仍然是实验性的,如果您有任何关于更好(或更正确)方法的建议,请告诉我” .我敢打赌,你在这个“实验”功能中发现了一个错误 -
你的意思是比多边形的边界框的尺寸大10%吗?
-
@jbaums 是的,我愿意。所以对于这个例子,在各个方向上都超出了康涅狄格州边界的最远范围 10% :)
-
为了简化您的示例代码,您可以用来自this recent question 的第 5-7 行替换所有涉及缓冲和区分形状的行。我也必须同意 jbaums:我昨天运行了你的代码并支持了这个问题,但是一旦我意识到这是 ggplot 和
coord_map的问题,我就停止了挖掘,因为 ggplot 太难了(至少对我来说) 调试!使用 base 或 lattice 绘图功能,我至少可以试一试。 -
@jbaums -- 不太正确。 raster 为
*定义了一个方法,当应用于Extent类对象时,它比这更聪明。试试extent(10,20,10,20) * 1.2看看它确实添加到每个维度。 (请注意,您必须乘以1.2才能在每个方向上获得 10% 的扩展。)如果您想查看Extent的*方法的底层代码,您可以通过键入getMethod("Arith", c("Extent", "numeric")).
标签: r map ggplot2 gis map-projections