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

R语言绘制cartogram统计地图时数据缺失group列问题求助

问题原因

你遇到的group列缺失问题是新旧空间数据格式的差异导致的:
原教程使用的是传统SpatialPolygonsDataFrame格式的空间数据,需要用broom::tidy()函数转成长表格才能适配ggplot2的geom_polygon,转换过程会自动生成用于区分不同多边形的group列和经纬度列。而你已经将数据转为了目前R生态主流的sf格式空间对象,ggplot2原生支持该格式的可视化,不需要手动找group列,也不需要手动指定坐标映射。


最优解法:直接使用geom_sf绘图

不需要修改原数据结构,直接替换图层函数即可,代码更简洁:

ggplot(data = afr_plot) +
  geom_sf(aes(fill = POP2005/1000000), linewidth = 0, alpha = 0.9) +
  theme_void()

如果需要完全匹配原教程的可视化效果,只要把原代码里的geom_polygon替换为geom_sf,删除x、y、group的映射,再把coord_map()替换为适配sf对象的coord_sf()即可:

ggplot() +
  geom_sf(data = afr_plot, aes(fill = POP2005/1000000), linewidth = 0, alpha = 0.9) +
  theme_void() +
  scale_fill_viridis(name="Population (M)", breaks=c(1,50,100, 140), guide = guide_legend( keyheight = unit(3, units = "mm"), keywidth=unit(12, units = "mm"), label.position = "bottom", title.position = 'top', nrow=1)) +
  labs( title = "Africa", subtitle="Population per country in 2005" ) +
  ylim(-35,35) +
  theme(
    text = element_text(color = "#22211d"), 
    plot.background = element_rect(fill = "#f5f5f4", color = NA), 
    panel.background = element_rect(fill = "#f5f5f4", color = NA), 
    legend.background = element_rect(fill = "#f5f5f4", color = NA),
    plot.title = element_text(size= 22, hjust=0.5, color = "#4e4d47", margin = margin(b = -0.1, t = 0.4, l = 2, unit = "cm")),
    plot.subtitle = element_text(size= 13, hjust=0.5, color = "#4e4d47", margin = margin(b = -0.1, t = 0.4, l = 2, unit = "cm")),
    legend.position = c(0.2, 0.26)
  ) +
  coord_sf()

备选解法:沿用原教程geom_polygon写法

如果需要完全复用原教程的图层逻辑,可以手动提取sf对象的坐标生成带group列的长表格:

# 提取sf对象的坐标,L1列即为多边形分组标识
afr_plot_coords <- as.data.frame(st_coordinates(afr_plot))
# 合并属性数据生成绘图用数据集
afr_plot_df <- afr_plot_coords %>%
  rename(long = X, lat = Y, group = L1) %>%
  left_join(afr_plot %>% mutate(group = row_number()) %>% st_drop_geometry(), by = "group")

# 即可使用原教程的geom_polygon代码绘图
ggplot() +
  geom_polygon(data = afr_plot_df, aes(fill = POP2005/1000000, x = long, y = lat, group = group) , size=0, alpha=0.9) +
  theme_void()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 03:57:05