Search code examples
rggplot2plotrastershapefile

Create interactive plot in R


I wonder if it is possible in R (RStudio) to have an interactive plot where user clicks in an image and this is used as input for upcoming processing. Here is my situation:

I have a raster that I plot

plot(NDVI[[4]])

[![enter image description here][1]][1]

Afterwards, I add a second layer containing polygon limits:

plot(fields, add=TRUE)

[![enter image description here][2]][2]

My objective is that user clicks on the image to select some of these polygons (let's say 3). Those clicks are used to identify those polygons which will later be used to derive the mean raster value inside the area they represent.

So far, I have been doing so updating a shapefile containing points, but I would like to make more interactive

points<-readOGR("Points_crops.shp") 
fields<-readOGR("Boundaries.shp")
fields_sub <- fields[!is.na(sp::over(fields, sp::geometry(points))), ]
NDVI_mean<-lapply(NDVI, FUN=function (NDVI) {data.frame(mean=extract(NDVI,fields_sub,fun=mean))})

Solution

  • For those interested, I have solved the issue using the click function. This will retrieve the coordinates of the point you click with the mouse. After that, you can convert them to spatialPoints setting a proj4string (same as the one of the raster of reference).

      points<-click(NDVI[[4]], n=5, xy=TRUE, show=TRUE)
      points$value<-NULL
      points<-SpatialPoints(points, proj4string = crs(S2_stack_crop[[2]]))
    

    Once I have the points as spatialPoints I can continue with the next step