在R ggmap中绘制自定义边框

问题描述 投票:0回答:1

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

r ggmap
1个回答
0
投票

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

非stf对象通常易于使用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)

以下是显示县界差异的图。不必使用颜色填充,而是用于突出显示特定区域。

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.