如何在 R 中提取 sf 形状的一部分?

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

说我有美国的

sf
型形状数据

usa <- giscoR::gisco_get_countries(country="USA")
# nrow(usa) is 1

现在包

usa
提供的
giscoR
数据包括阿拉斯加和一些太平洋岛屿。有没有办法从整个形状中提取连续的美国作为较小的
sf
数据?或者我可以在
ggplot
+
geom_sf
框架内绘制连续的美国吗?

r ggplot2 spatial sf
2个回答
0
投票

您可以使用

sf::st_crop
将坐标修剪到您选择的任何位置,然后根据您的喜好绘制。这是使用
ggplot
的完整代表:

giscoR::gisco_get_countries(country = "USA") |>
  sf::st_crop(c(xmin = -125, xmax = -60, ymin = 20, ymax = 60)) |>
  ggplot2::ggplot() + 
  ggplot2::geom_sf()
#> Warning: attribute variables are assumed to be spatially constant throughout all
#> geometries

创建于 2023-05-18 与 reprex v2.0.2


0
投票

您描述的输出——国家层面的单行数据——是国家(即国家)层面数据的预期行为。阿拉斯加和太平洋岛屿(我想是夏威夷)都是美国的一部分。

要分别获得较低的 48 个,您可能希望从地方行政单位(例如美国各州)开始,并根据需要过滤掉它们。一个好地方是

{tigris}
包。

所以考虑这段代码:

library(tidyverse)
library(tigris)
library(sf)

states <- states(cb = FALSE, resolution = '20m') %>%
  filter(!STUSPS %in% c('HI', 'AK', 'PR', 'GU', 'VI', 'AS', 'MP')) %>% 
  select(NAME, STUSPS) 


ggplot(data = states) +
  geom_sf() +
  geom_sf_label(aes(label = STUSPS)) +
  theme_void()

准备好 48 个状态的对象后,您可以通过

dplyr::summarise()
调用将其合并为单个多多边形几何体。

lower_48 <- states %>% 
  summarise()

ggplot(data = lower_48) +
  geom_sf()

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