geom_sf missing geometry with SpatialPolygonsDataFrame

68 Views Asked by At

I'm working with some GPS collared animals and using LoCoH.a function in the adehabitatHR package to generate 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()

Everything works until I try to plot the resulting object with ggplot. I get the following error:

> 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.

I verified that the class for 'birds.area' is the appropriate format which is an issue identified in other posts, however I cannot figure out why geometry would be missing from a SpatialPolygonsDataFrame.

1

There are 1 best solutions below

1
On

You need to transform birds.area from a SpatialPolygonsDataFrame to an sf object, before using ggplot and geom_sf. You can do this with:

library(sf)
birds.area <- st_as_sf(birds.area)