代码之家  ›  专栏  ›  技术社区  ›  ikashnitsky

无缝拟合两个sf多边形

  •  23
  • ikashnitsky  · 技术社区  · 7 年前

    问题所在

    假设我们有两个应该无缝边界的shapefile。只是,他们没有。有没有办法迫使他们彼此无缝隙地坚持?

    enter image description here


    具体案例

    我有两个形状文件:一个用于欧洲地区-- REG ,另一个用于邻国-- NEI . 两个形状文件都来自 Eurostat repository 而且应该很好地结合在一起;但差距很小。此外,我需要简化多边形,然后间隙变得非常明显。


    我能想到的最好的

    我尝试了几种方法,但都没有成功。实现我所看到的预期结果的唯一方法需要以下步骤:

    • 创建一条线sf,仅在我的形状文件之间使用边界;
    • 从这条线创建一个足够大的缓冲多边形,以覆盖所有间隙;
    • 将此缓冲区加入并分解到邻居的shapefile-- 内伊 ;
    • 剪掉展开的 内伊 使用 规则 形状文件。

    显然,这是一个相当笨拙的解决方法。

    还有更好的方法吗?


    中的可复制示例 this gist


    一个简单的例子

    # install dev version of ggplot2
    devtools::dev_mode()
    devtools::install_github("tidyverse/ggplot2")
    
    library(tidyverse)
    library(sf)
    library(rmapshaper) 
    library(ggthemes)
    
    
    # load data
    source(file = url("https://gist.githubusercontent.com/ikashnitsky/4b92f6b9f4bcbd8b2190fb0796fd1ec0/raw/1e281b7bb8ec74c9c9989fe50a87b6021ddbad03/minimal-data.R"))
    
    # test how good they fit together
    ggplot() + 
            geom_sf(data = REG, color = "black", size = .2, fill = NA) +
            geom_sf(data = NEI, color = "red", size = .2, fill = NA)+
            coord_sf(datum = NA)+
            theme_map()
    
    ggsave("test-1.pdf", width = 12, height = 10)
    
    # simplify
    REGs <- REG %>% ms_simplify(keep = .5, keep_shapes = TRUE)
    NEIs <- NEI %>% ms_simplify(keep = .5, keep_shapes = TRUE)
    
    
    ggplot() + 
            geom_sf(data = REGs, color = "black", size = .2, fill = NA) +
            geom_sf(data = NEIs, color = "red", size = .2, fill = NA)+
            coord_sf(datum = NA)+
            theme_map()
    
    ggsave("test-2.pdf", width = 12, height = 10)
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Gilles San Martin    7 年前

    ms_simplify 似乎适用于您的最小示例,但您需要首先将2个“shapefile”分组为一个“shapefile”。如果需要,在简化边界后,可以很容易地将其拆分。
    (注意:我的版本 rmapshaper 在以下情况下返回错误 ms\U简化 sf 对象这就是为什么我改变了我的 tmp 中的对象 sp 对象具有 as(tmp, "Spatial") )

    NEI <- st_transform(NEI, st_crs(REG)$epsg)
    tmp <- rbind(REG , NEI)
    tmp <- ms_simplify(as(tmp, "Spatial"), keep = .1, keep_shapes = T)
    ggplot() + geom_sf(data = st_as_sf(tmp)) + theme_bw()
    

    enter image description here