[R] retrieve x y coordinates of points in current plot

Jannis bt_jannis at yahoo.de
Sat Mar 5 19:54:28 CET 2011


On 03/05/2011 07:25 PM, Greg Snow wrote:
> It is not completely clear what you are trying to accomplish.  Do you want to draw a shape in the plot then identify all the points in that shape?  You could use locator (with type='l') to draw a polygon, then there are functions in add on packages (mostly the spatial ones) that will detect which points are within a polygon that you could use with the raw data and the polygon created.
>
> If that is not what you want, then maybe describe your goals in more detail (examples are good if you can give one).
>
Thats exactly what I want. drawing a polygon in a plot and searching for 
the points inside the polygon. I managed to create that polygon and to 
check which points are inside but only by supplying my function with the 
coordinates of the points. Now I was wondering whether it is also 
possible to retrieve these coordinates from the plot (similar to 
par()$usr and similar...).


ideally it would work as follows:

x<-rnorm(20)
y=rnorm(20)
plot(x,y)
points.in.poly <- identify.poly() #see below
#now click on the plot to identify the points

Right now it only works like
points.in.poly <- identify.poly(x,y)

Anyway, supplying the points is not too complicated, it would just be 
easier to do without.

identify.poly <- function(x,y,col.points='red')
{
   require(sp)
   exit=FALSE
   i=0
   coords.all <- list(x=vector(length=100),y=vector(length=100))
   coords.all$x[1:100]<-NA
   coords.all$y[1:100]<-NA

   while (i<100)
     {
       coords.t <- locator(n=1)
       exit=!point.in.polygon(coords.t$x,coords.t$y,
                              par()$usr[c(1,2,2,1)],par()$usr[c(3,3,4,4)])
       if (exit)
         {
           break
         }
       i=i+1
       points(coords.t,col=col.points,pch='+')

       coords.all$x[i] <- coords.t$x
       coords.all$y[i] <- coords.t$y
       if (i>1)
         points(coords.all$x[(i-1):i],coords.all$y[(i-1):i],lty=2,
                col=col.points,type='l')
     }
   points(coords.all$x[c(i,1)],coords.all$y[c(i,1)],lty=2,
          col=col.points,type='l')
   coords.all$x <- na.omit(coords.all$x)
   coords.all$y <- na.omit(coords.all$y)


   points.inpoly <- point.in.polygon(point.x=x,point.y=y,
                                     pol.x=coords.all$x,pol.y=coords.all$y)
   
points(x[points.inpoly==1],y[points.inpoly==1],pch=par()$pch,col=col.points)
   data.return=list(in.poly=!!points.inpoly,x=x,y=y)
}



More information about the R-help mailing list