简体   繁体   中英

how to create a polygon and get it coordinates with spatial data in R

I Would like to know if there is a way to set a polygon interactively in a plot spatial data image and get It's coordinates. I know there is the locator() function, but I would like to set a circles or square and get it coordinates.

The question has been updated so maybe I better understand the aim now. You want to plot a region with a lot of boundaries and then click a polygon on top? With the shape file provided in the comment you can do:

library(spatstat)
library(sp)
library(maptools)

obj <- readShapeSpatial("mun_lin.shp")
region <- unmark(as(obj, "psp"))
x11() # Necessary when using RStudio (at least on my machine)
plot(region, main = "")
x <- clickpoly(add = TRUE, col = 2, lwd = 2) # Start locator overlayed on region

Then you just left click the points you need and middle/right click when you are done. The points are stored as a window ( owin ) in x . You can get a list with the x,y coordinates:

vertices(x)

So I had used drawPoly() from the raster library, here is the code:

library(spatstat)
library(raster)
#load the shapefile
plot(shape)#plot it
points(data.coords,col="green",pch=4)#add data coordenates points
polygon<- drawPoly()#draw a polygon in the window
#take it limits
xlim<-polygon@bbox[1,]
ylim<-polygon@bbox[2,]
new_points<-ppp(data.coords[,1], data.coords[,2], xlim, ylim)#take points inside the polygon

new_points<- data.frame(new_points)#convert to data.frame

plot(shape)
points(new_points ,col="red",pch=4)#plot the selected points in the shape

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM