geom_sf报错缺失geometry:SpatialPolygonsDataFrame绘图故障排查
问题:SpatialPolygonsDataFrame使用geom_sf()绘图提示缺失geometry字段
我正在处理佩戴GPS项圈的动物数据,用adehabitatHR包的LoCoH.a()函数生成了SpatialPolygonsDataFrame,代码如下:
library(tidyverse) library(lubridate) library(adehabitatHR) library(sp) library(sf) library(ggplot2) library(maptools) coordinates(birds1) <- c("x", "y") birds.xy <- SpatialPoints(birds1) birds.area <- LoCoH.a(birds.xy, a = 5000, unin = c("m"), unout = c("km2"), duplicates = "random") class(birds.area) ggplot(birds.area) + geom_sf()
执行代码后已验证birds.area是合法的SpatialPolygonsDataFrame,但调用geom_sf()绘图时出现错误:
> ggplot(birds.area) + geom_sf() Regions defined for each Polygons Error in `geom_sf()`: ! Problem while computing stat. ℹ Error occurred in the 1st layer. Caused by error in `compute_layer()`: ! `stat_sf()` requires the following missing aesthetics: geometry Run `rlang::last_trace()` to see where the error occurred.
无法理解为何SpatialPolygonsDataFrame会提示缺失geometry,请求排查解决。
解决方案
核心原因
geom_sf()是ggplot专为sf对象设计的图层,而LoCoH.a()返回的是sp包的SpatialPolygonsDataFrame,两种空间数据结构的存储逻辑不同:sf对象依赖显式的geometry列,而sp对象的空间信息是存储在@polygons插槽里的,因此geom_sf()无法识别sp对象的空间信息,从而抛出缺失geometry的错误。
修复步骤
将sp对象转换为sf格式后再绘图,具体修改如下:
library(tidyverse) library(lubridate) library(adehabitatHR) library(sp) library(sf) library(ggplot2) library(maptools) coordinates(birds1) <- c("x", "y") birds.xy <- SpatialPoints(birds1) birds.area <- LoCoH.a(birds.xy, a = 5000, unin = c("m"), unout = c("km2"), duplicates = "random") # 将SpatialPolygonsDataFrame转换为sf对象 birds.area_sf <- sf::st_as_sf(birds.area) # 使用sf对象绘图 ggplot(birds.area_sf) + geom_sf()
补充说明
如果不想转换格式,也可以直接使用sp包原生的绘图函数:
plot(birds.area)
但ggplot的geom_sf()仅支持sf对象,因此格式转换是适配ggplot绘图流程的最优方案。
内容的提问来源于stack exchange,提问作者Jason P
相关产品推荐
相关产品推荐

