I have a ggplot map with a location and would like to add a buffer (spatialPolygon) around this location. However, when I add the buffer to my ggplot, I get the error "Error in FUN(X[[i]], ...) : object 'x' not found.". I am not sure where to go from here.
my code
library(sp)
library(geosphere)
library(geobuffer)
library(ggplot2)
library(rworldmap)
library(rworldxtra)
# my location
colony.df <- data.frame(Long = c(-61.313002), Lat = c(-51.714750)) # keep as dataframe for map
colony <- data.frame(Long = c(-61.313002), Lat = c(-51.714750)) # transform for buffer
# Convert location dataframe to spatial points (SpatialPointsDataFrame)
coordinates(colony) <- cbind(colony$Long, colony$Lat)
# assign a CRS to the spatial object
proj4string(colony) = CRS("+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0")
# create buffer around the colony
buf10km<- geobuffer_pts(xy = colony, dist_m = 10000)
# load shapefiles for ggplot
worldMap <- rworldmap::getMap(resolution = "high")
fi <- worldMap[which(worldMap$NAME == "Falkland Is."), ]
# create ggplot
p <- ggplot(colony.df) +
# countries
geom_polygon(data = fi, aes(long, lat, group = group), color = "grey20", fill = "grey60", size = 0.3) +
# data
geom_point(aes(x = Long, y = Lat), size = 3) +
# visuals
scale_x_continuous(breaks = scales::pretty_breaks(5), name = "Longitude (W)", expand = c(0, 0)) +
scale_y_continuous(breaks = scales::pretty_breaks(5), name = "Latitude (S)", expand = c(0, 0)) +
coord_quickmap(xlim = c(-64,-60), ylim = c(-50,-53)) + # zoomed out
theme_bw() +
theme(axis.text.x = element_text(size = 10),
axis.text.y = element_text(size = 10),
axis.title.x = element_text(size = 12, vjust = 0),
axis.title.y = element_text(size = 12, vjust = 2),
panel.grid = element_blank())
p
# add buffer
p <- p + geom_polygon(aes(x=x, y=y), data = buf10km, color = "red", alpha = 0.2, size = .2)
p
