使用R绘制地图报错:stat_sf缺失geometry美学属性求解决
问题描述
我希望使用以下数据集:
以及以下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()
- 额外检查项:
- 运行
class(mymap),确认结果包含sf类,说明空间属性保留成功 - 检查
Total列是否存在缺失值,可通过filter(!is.na(Total))过滤后再绘图 - 确保关联列的内容格式一致(比如编码不能有大小写、空格差异)
- 运行
内容的提问来源于stack exchange,提问作者Aman
相关产品推荐
相关产品推荐

