【问题标题】:Draw customized borders in R ggmap在 R ggmap 中绘制自定义边框
【发布时间】:2019-12-03 07:53:58
【问题描述】:

我可以使用 R 的 ggmap 例程轻松创建带有县界或州界的美国地图。在我的问题设置中,我有一个连续县的自定义分组(可能跨越州界),我只想绘制这个自定义组的边界,即不显示任何自定义组中的内部县边界。非常感谢任何关于如何做到这一点的指示。

【问题讨论】:

    标签: r ggmap


    【解决方案1】:

    使用 ggplot2 和 sf 可以制作这种类型的地图。它依赖于使用 sf 对象和 sf::st_union() 函数。

    非 sf 对象通常很容易使用 st_as_sf 强制。

    library(sf)
    
    #Using the included nc dataset from sf package
    nc <- st_read(system.file("shape/nc.shp", package="sf"))
    
    # Arbitrarily select county near the middle of the state
    single_county <- nc %>% filter(NAME == "Randolph")
    
    single_county_plot <- ggplot() + 
      geom_sf(data = nc) + 
      geom_sf(data = single_county, fill = 'red') +
      ggtitle('Single County, all borders')
    
    #select all counties touching Randolph county
    touching_single <- nc[st_touches(single_county, nc, sparse = FALSE),]
    
    touching_plot <- ggplot() + 
      geom_sf(data = nc) + 
      geom_sf(data = single_county, fill = 'red') + 
      geom_sf(data = touching_single, fill = 'green') +
      ggtitle('Multiple Counties,  all borders')
    
    # Use st_union to join touching_single, which removes distinct boundaries
    touching_unioned <- st_union(touching_single)
    
    # Plotting it all
    full_plot <- ggplot() +
      geom_sf(data = nc) + 
      geom_sf(data = single_county, fill = 'red') + 
      geom_sf(data = touching_unioned, fill = 'green') + 
      ggtitle('All counties, some borders unioned')
    
    full_plot_uncolored <- ggplot() +
           geom_sf(data = nc) + 
           geom_sf(data = single_county) + 
           geom_sf(data = touching_unioned) + 
           ggtitle('All counties, some borders unioned uncolored')
    
    cowplot::plot_grid(single_county_plot, touching_plot, full_plot, full_plot_uncolored)
    
    

    下面是显示县边界差异的图表。使用颜色填充不是必需的,但用于突出显示特定区域。

    【讨论】:

    • 感谢您的详细回复。这有点超出了我的 R 技能,但我一定会试一试,如有任何问题,我都会回复你。
    • 超越你的技能,但继续努力。这里有很多信息:r-spatial.org
    猜你喜欢
    • 2018-08-31
    • 1970-01-01
    • 2014-04-01
    • 2021-05-27
    • 2012-01-15
    • 1970-01-01
    • 1970-01-01
    • 2014-02-21
    • 1970-01-01
    相关资源
    最近更新 更多