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

使用R绘制地图报错:stat_sf缺失geometry美学属性求解决

问题描述

我希望使用以下数据集:
数据集
以及以下shapefile:
Shapefile
创建地图,编写的R代码如下:

library("tidyverse")
library("dplyr")
library("sf")
library("ggplot2")
library("tmap")
library("tmaptools")
library("RColorBrewer")

data = readr::read_csv("C:/Users/amanm/Desktop/annualincomedata2.csv")

localauthorities2 <- read_sf("C:/Users/amanm/Desktop/localauthorities2.dbf")

mymap <- merge(data,localauthorities2)

ggplot(mymap) + geom_sf(aes(fill = Total)) + scale_fill_viridis_c()

运行后出现错误:

> ggplot(mymap) + geom_sf(aes(fill = Total)) + scale_fill_viridis_c()
Error in `check_required_aesthetics()`:
! stat_sf requires the following missing aesthetics: geometry
Run `rlang::last_error()` to see where the error occurred.
解决建议
  • 问题核心:merge()函数会将sf空间对象转换为普通data.frame,导致geometry空间列丢失,而geom_sf()必须依赖该列绘制地图。
  • 修复代码:用dplyr的连接函数替代merge(),它会保留sf对象的空间属性:
# 替换原merge语句,注意替换"匹配列名"为两个表的共同关联列(如地区编码、名称)
mymap <- localauthorities2 %>% 
  left_join(data, by = "匹配列名")

# 若两个表的关联列名称不同,可指定对应关系:
# mymap <- localauthorities2 %>% 
#   left_join(data, by = c("shapefile中的列名" = "数据集中的列名"))

# 正常绘图
ggplot(mymap) + geom_sf(aes(fill = Total)) + scale_fill_viridis_c()
  • 额外检查项:
    1. 运行class(mymap),确认结果包含sf类,说明空间属性保留成功
    2. 检查Total列是否存在缺失值,可通过filter(!is.na(Total))过滤后再绘图
    3. 确保关联列的内容格式一致(比如编码不能有大小写、空格差异)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 05:06:42