You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

usmap转sf对象遇“polygons not closed”错误的解决求助

解决方案

方案a:直接获取指定区域的县级SF对象

无需手动转换usmap的数据,直接用tigris包可直接获取符合需求的县级SF对象,支持指定多个州且包含阿拉斯加地理数据:

library(tigris)
library(dplyr)

# 指定目标州的缩写
target_states <- c('AK','CO','ID','MT','UT','OR','WA','WY','ND','SD')

# 获取多个州的县级SF数据并合并
counties_sf <- counties(state = target_states, cb = TRUE) %>%
  filter(STATEFP %in% fips_codes$fips[fips_codes$state %in% target_states])

# 验证数据结构
head(counties_sf)
  • cb = TRUE用于获取简化版地理数据(适合快速绘图),需要高精度数据可去掉该参数
  • 数据自带FIPS编码、县名等属性,无需手动处理分片问题

方案b:修复usmap数据转SF时的多边形未闭合问题

如果坚持使用usmap的数据,问题根源是部分分片的坐标首尾点不重合,需手动闭合多边形。修改转换代码如下:

library(usmap)
library(sf)
library(dplyr)

# 原始数据获取
df <- usmap::us_map('counties') %>%
  filter(abbr %in% c('AK','CO','ID','MT','UT','OR','WA','WY','ND','SD')) %>%
  rename(state=abbr)

# 自定义函数:闭合多边形(确保首尾坐标一致)
close_polygon <- function(x) {
  coords <- cbind(x$x, x$y)
  # 检查首尾是否相同,不同则添加首点到末尾
  if (!all(coords[1,] == coords[nrow(coords),])) {
    coords <- rbind(coords, coords[1,])
  }
  st_polygon(list(coords))
}

# 按县和分片处理并闭合多边形
MtWc <- lapply(split(df, list(df$county, df$piece), drop = TRUE), close_polygon)
MtW  <- st_sfc(MtWc, crs = usmap_crs()@projargs)

# 匹配对应分片的FIPS编码
county_fips <- df %>%
  group_by(county, piece) %>%
  summarise(fips = first(fips), .groups = 'drop') %>%
  arrange(county, piece)

MtW_sf <- st_sf(
  data.frame(fips = county_fips$fips, county = names(MtWc)),
  geometry = MtW
)
  • 核心是close_polygon函数,自动检查并补全首尾坐标,确保多边形闭合
  • 修复了原代码中unique(d$fips)的错误,改为从原数据中按分片提取对应FIPS编码

内容的提问来源于stack exchange,提问作者M3Lba

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 03:11:15