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

更新R包后,如何用usmap在县地图添加州边界与州缩写?

解决usmap更新后添加州边界/缩写报错“找不到对象x”的问题

问题背景

我使用usmap包,基于存储在county变量中的数据绘制美国各县的数值地图。在更新R及所有包之前,可通过以下代码生成带有粗州边界和州缩写的县地图:

library(ggplot2)
library(usmap)
centroid_labels = usmapdata::centroid_labels("states")
plotdf = data.frame(cbind(county$FIPS,county$SES)); plotdf[,2] = as.numeric(as.character(plotdf[,2])); names(plotdf) = c("fips", "SES");
plot_usmap(data = plotdf, values = "SES", color = NA) +  # color = NA removes county boundary lines
geom_polygon(data = usmapdata::us_map(regions = "states"), aes(x, y, group = group), fill = NA, linewidth = 1, color = "black") + # Keep state boundary lines
geom_text(data = centroid_labels, aes(x = x, y = y, label = abbr), fontface = "bold", colour = "gray12", size = 3)

更新后代码报错提示“找不到对象x”,目前仅能绘制县地图,无法添加州边界和州缩写。

解决方案

usmap更新后,plot_usmap使用的投影坐标系与usmapdata直接返回的数据不再兼容,需要用usmap_transform函数转换州边界和中心点标签的坐标,适配usmap的投影。修正后的代码如下:

library(ggplot2)
library(usmap)

# 处理原始数据(逻辑与原代码一致)
plotdf <- data.frame(
  fips = county$FIPS,
  SES = as.numeric(as.character(county$SES))
)

# 获取州边界数据并转换坐标
state_map <- usmap_transform(usmapdata::us_map(regions = "states"))

# 获取州中心点标签并转换坐标
centroid_labels <- usmap_transform(usmapdata::centroid_labels("states"))

# 绘制带州边界和缩写的县地图
plot_usmap(data = plotdf, values = "SES", color = NA) +
  geom_polygon(
    data = state_map,
    aes(x = x, y = y, group = group),
    fill = NA, linewidth = 1, color = "black"
  ) +
  geom_text(
    data = centroid_labels,
    aes(x = x, y = y, label = abbr),
    fontface = "bold", colour = "gray12", size = 3
  )

说明

  • usmap_transform会将usmapdata返回的地理数据转换为与plot_usmap一致的投影坐标系,确保x、y字段能被ggplot正确识别。
  • 原代码直接使用未转换的地理数据,更新后usmap的内部投影逻辑变更,导致坐标字段不匹配,触发“找不到对象x”的错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 14:50:09