Create interactive plot in R - 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))})

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

Related

How can I read coordinate values from the plot graph?

I have drawn a plot graph enter image description here
I want to read the coordinate values of the intersection dot in the following graph.enter image description here
Are there any packages or functions to do this?
Thanks for your answer.

geoviews/geopandas/shapely problem displaying polygons from a shapefile

I am trying to overlay a shapefile representing the range of Coast Redwoods onto some other data I'm processing in geoviews. I can successfully plot the data using cartopy and matplotlib. GeoPandas reads the shapefile, but passing the GeoDataFrame or individual shapely polygons to gv.Shape (as in the geoviews user guide under "Shape") consistently results in
AttributeError: 'list' object has no attribute 'xy'
I am not sure whether the problem is in Shapely or in Geoviews. I suspect geoviews because geopandas is able to reproject and plot the polygons.
I've put up a notebook demonstrating the problem and providing the shapefile.
Any help or ideas much appreciated.
I was having the same issue, then i went ahead and converted my GeoDataFrame to EPSG:4326 as follows:
projected_df = original_df.to_crs('EPSG:4326')
Originally I was in EPSG:4269 (Albers Equal Area) and thought adding that to an Albers Equal Area projection would work but I think you need to start your data with EPSG:4326 and then work with projections with Geoviews.
Let me know if that does the trick.

R: Clip a shapefile boundary out of a generated image

I generated an image of ordinary kriged predictions. I have a shapefile of a boundary line and I'd like to crop the ordinary kriged predictions in the shape of that shapefile.
This is the code I use to generate the image:
image(OK.pred,loc=grid,axes=F,useRaster=TRUE). I just want to clip an object out of the image -- when I plot them, they overlay perfectly.
It's almost identical to the issue here, https://gis.stackexchange.com/questions/167170/is-it-possible-to-clip-a-shapefile-to-an-image-in-r, but I'm relatively new to R and got totally lost with the netcdf file part.
I found a bunch of code on how to clip rasters, but I just can't figure out how to even save an image into a variable let alone transform it to a raster in order to clip it. Any help would be much appreciated!
OK.pred<-krige.conv(gambling.geo,coords = gambling.geo$coords, data=gambling.geo$data, locations=grid,krige=krige.control(obj.model=gambling.vario.wls))
ordinarykrig = image(OK.pred,loc=grid,axes=F,useRaster=TRUE)
Macau <- readOGR("MAC_adm0.shp")
x <- crop(?...)
Taken from http://leg.ufpr.br/geoR/tutorials/kc2sp.R:
You need to convert the kriging output to a Spatial object before you can pass it to mask(). The following should do it:
OK.pred<-krige.conv(gambling.geo,coords = gambling.geo$coords, data=gambling.geo$data, locations=grid,krige=krige.control(obj.model=gambling.vario.wls))
GT.s <- points2grid(SpatialPoints(as.matrix(grid)))
reorder <- as.vector(matrix(1:nrow(grid), nc=slot(GT.s, "cells.dim")[2])[,slot(GT.s, "cells.dim")[2]:1])
SGDF.s <- SpatialGridDataFrame(grid=GT.s, data=as.data.frame(OK.pred[1:2])[reorder,])
r<-raster(SGDF.s)
x<-mask(r, Macau)

Changing the extent and resolution of raster layers in R for successful stacking

I am trying to create a species distribution model in R. I have created raster layers in ArcMap and have imported them into R. They cannot be stacked unless the extents are exactly the same and they all have the same number of rows and columns.
However, when I alter these factors to successfully stack them they lose all their values and my stacked data frame is just filled with NAs.
Does anyone know how I can alter the extent and resolution of my raster layers so they can be successfully stacked -- so I can then attach environmental info to presence points.
Cheers
One way to do this is to choose a raster that has the projection and extent that you want and use that as a template for the others
For example, if you have rasterA and rasterB. You can use projectRaster() to make a new version of rasterA with the same extent and resolution as rasterB. You should then be able to stack new.rasterA & rasterB.
new.rasterA <- projectRaster(rasterB, rasterA) # define the projection and extent
r.stack <- stack(new.rasterA, rasterB) # add them to a raster stack object
I had the same issue and I solved this in arcgis by snapping each raster to a mask of my study area.
This can be done by clicking geoprocessing -> environments -> processing extent - then select a layer you want to snap to in the snap raster box. I did this before I extracted (clipped) each layer and it worked perfectly. You can check the extent in properties when you are done for each layer you do to double check before you upload them into R.

R animate ggplot of lat/lon coords using date

I have a data set with about 180,000 observations. I can plot all of them using lat/lon coords and ggplot. When I plot them all at once, i get big blob. Any tips on how to create an animation, where each frame will plot all of the plots on a given date? Note that there are often many observations per date.
Thanks in advance
my data has the following columns.
Created Date, Latitude, Longitude
3/19/14, 40.62143617 -73.92598905
3/19/14 40.65808826 -73.84443243
3/18/14 40.64067217 -73.95307493
I used ggplot2 to plot all of the coords with the code below.
require(ggplot2)
cold <- read.csv(fn, header=TRUE)
r <- ggplot(cold, aes(x=Longitude, y=Latitude,)) + geom_point(size=.9, alpha=.02)
The tkexamp function in the TeachingDemos package can be used to make an interactive GUI for your own functions and one of the controls it has an animate control.
Just write a function that takes the date (as a number) as and argument and plots the subset of the data based on that date, then pass that function along with a list specifying the animate control to tkexamp. There will be a slider that you can use to move through time, or click the play button next to the slider and it will scroll through for you.
The last 2 examples for tkexamp show using it with ggplot2 and the final example for the USCrimes data set (TeachingDemos package) shows using the animate control for tkexamp. Combine these with your data and you will be able to view your data animated.

Resources