I would like to generate a buffer in the shape of an ellipse around each point in a SpatialPointsDataFrame, meaning in the end I would like to have a polygon for each point in my spatial data frame that is shaped like an ellipse extending the original point 130 km latitudinal and 70 km longitudinal.
I tried using the st_ellipse function but run into the issue that the resulting polygon plots in a random location instead of as a buffer around the point it was generated for.
Maybe someone has an idea, what might be going wrong here or has a suggestion for a different way to generate an ellipse around a spatial point.
Please see the code I used below.
Thank you very much in advance!
# example data frame
ID<-"point1"
longitude<- -120.628
latitude<- 36.64
spp<-data.frame(ID,longitude,latitude)
projection<-"+proj=laea +lat_0=45 +lon_0=-100 +x_0=0 +y_0=0 +a=6370997 +b=6370997 +units=m +no_defs"
# convert to st object to be able to use st_ellipse function
stp<-st_as_sf(spp, coords = c("longitude", "latitude"))
# assign same projection as background
stp<-stp %>% st_set_crs(st_crs(world2_proj))
# generate ellipse around point (70 km longitudinal; 130 km latitudinal)
stp_elp<-st_ellipse(stp, ex=70000, ey=130000)
#convert back to spatial polygon
elp_poly<-as(stp_elp, "Spatial")
# convert into a SpatialPolygonDataFrame
df<- data.frame(id = getSpPPolygonsIDSlots(elp_poly))
row.names(df) <- getSpPPolygonsIDSlots(elp_poly)
spdf <- SpatialPolygonsDataFrame(elp_poly, data =df)
# change projection to match to background
crs(spdf)<-projection
both SpatialPolygonsDataFrame have the same projection:
spdf
class : SpatialPolygonsDataFrame
features : 1
extent : -70120.63, 69469.03, -129772.7, 129846 (xmin, xmax, ymin, ymax)
crs : +proj=laea +lat_0=45 +lon_0=-100 +x_0=0 +y_0=0 +ellps=sphere +units=m +no_defs
variables : 1
names : id
value : ID1
world2_proj
class : SpatialPolygonsDataFrame
features : 209
extent : -12240565, 11932463, -12523922, 11616224 (xmin, xmax, ymin, ymax)
crs : +proj=laea +lat_0=45 +lon_0=-100 +x_0=0 +y_0=0 +ellps=sphere +units=m +no_defs
variables : 3
names : NAME, GMI_CNTRY, REGION
min values : Afghanistan, AFG, Antarctica
max values : Zimbabwe, ZWE, Sub Saharan Africa
# But when I try to plot them on top of each other, the new polygon (in red) plots in a random location away from the original location (blue cross).
# plot on top of background to see if function worked
plot(crop(world2_proj,e))
plot(spdf, add=T, col="red")
The new polygon (in red), plots in a random location away from the location that was used to generate the ellipse from
question from:
https://stackoverflow.com/questions/65897418/extent-spatialpoints-in-to-spatialpolygon-in-the-shape-of-an-ellipse