I am trying to plot a simple polygon on a map to denote the area I am interested in. To date, I have defined the polygon as and am able to plot it on it's own.
poly <- st_polygon(list(as.matrix(data.frame(lat = c(40, 40, 60, 60, 40),
lon = c(-60, -40, -40, -60, -60))))) #EDIT: these are lat/lon coordinates
ggplot() +
geom_sf(data = poly,
aes(geometry = geometry),
col = "red)
However, I need to add a basemap so that I can show the placement of this polygon in relation to other spatial elements.
# Attempt #1: stamenmaps basemap
grid_box <- c(left = -70,
right = -30,
bottom = 35,
top = 70)
base <- get_stamenmap(grid_box, zoom = 6, maptype = "terrain-background", color = "color")
ggmap(base) +
geom_sf(data = poly,
aes(geometry = geometry),
col = "red")
Coordinate system already present. Adding new coordinate system, which will replace the existing one.
Error in `geom_sf()`:
! Problem while computing aesthetics.
ℹ Error occurred in the 4th layer.
Caused by error in `FUN()`:
! object 'lon' not found
Run `rlang::last_error()` to see where the error occurred.
The only approach I found for adding a crs to my polygon is below (st_transform & st_as_sf didn't work), but this dramatically changed the scale of the coordinates and still doesn't plot.
# Attempt #2: new CRS
poly <- st_polygon(list(as.matrix(data.frame(lon = c(-62, -43, -43, -62, -62),
lat = c(43, 43, 70, 70, 43))))) %>%
st_sfc(crs = 3857)
ggmap(base) +
geom_sf(data = poly,
aes(geometry = geometry),
col = "red")
Coordinate system already present. Adding new coordinate system, which will replace the existing one.
Error in `geom_sf()`:
! Problem while computing aesthetics.
ℹ Error occurred in the 4th layer.
Caused by error in `FUN()`:
! object 'lon' not found
Run `rlang::last_error()` to see where the error occurred.
How can I get this polygon to plot over my basemaps?