r raster statistics per grid cell zone - r

I would like to calculate grid cell statistics in zones that are within graticules (see plot).
Getting the cellstats for the shown grid cell is not difficult, but how could this be done for all grid cells?
library(raster)
filename <- system.file("external/test.grd", package="raster")
r=raster(filename)
plot(r)
e=extent(180000,181000,330000,331000)
plot(e,add=T)
grid()
x=crop(r,e)
cellStats(x,mean)

Your reproducible example did not work for me as I am not sure why r[r>500]=1 and r[r<=500]=NA are used while your original plot is different?! Plus, I was not sure what rx is?! One way to do this as below:
library(raster)
filename <- system.file("external/test.grd", package="raster")
r=raster(filename)
# r[r>500]=1
# r[r<=500]=NA
plot(r)
xmin <- seq(178000, 181000, 1000)
xmax <- seq(179000, 182000, 1000)
ymin <- seq(329000, 333000, 1000)
ymax <- seq(330000, 334000, 1000)
zonal.mtx <- matrix(nrow=length(xmin), ncol=length(ymin))
library(spatialEco)
for (i in 1:length(xmin)){
for (j in 1:length(ymin)){
e=extent(xmin[i],xmax[i],ymin[j],ymax[j])
plot(e,add=T)
grid()
p <- as(e, 'SpatialPolygons')
crs(p) <- crs(r)
p$ID=j
p <- SpatialPolygonsDataFrame(p,p#data)
zonal.mtx[i,j] <- zonal.stats(x=p, y=r, stat=sum, trace=TRUE, plot=TRUE)
#print(zonal.mtx[i,j])
}
}
Note: this plots each portion of the data while calculating zonal stats. I am sure you already know that you can also define your own function for using in zonal.stats rather than sum, mean etc.

Related

Extract the results plotted in the margin of the levelplot function

How can i extract the results plotted in the margin of the levelplot function?
Or is there a function that does the same thing?
I'm searching for something like a table...
Best regards,
library(raster)
library(rasterVis)
library(gridExtra)
f <- system.file("external/test.grd", package="raster")
r <- raster(f)
x <- levelplot(r, margin=T)
From the help page of rasterVis::levelplot:
[These] marginal graphics show the column (x) and row (y) summaries of
the Raster* object. The summary is computed with the function
mean.
You should use the raster::zonal function to compute them:
rx <- init(r, 'x')
mx <- zonal(r, rx, FUN = mean)
plot(mx, type = 'l')

Use animate() with series of levelplots in R raster

I have a time series of 25 yearly land cover rasters. As this is categorical data, I use levelplot(inputRaster) (part of the rasterVis library) to plot a single raster. However, I would like to sequentially plot the yearly rasters, as the animate function of the raster library does. When I use
rasStack <- stack(listOfRasters)
animate(rasStack)
The result does not have a categorical legend.
So in short: how can I combine the functionalities of levelplot and animate?
Function animate only accepts raster objects as input. You can try saveGIF to animate levelplots:
library(raster)
library(rasterVis)
library(animation)
library(classInt)
r <- raster(ncol=40, nrow=20)
r[] <- rnorm(n=ncell(r))
s <- stack(x=c(r, r*r, r*r*r, r*r*r*r))
classes <- classIntervals(values(r), n=5, style="fisher", precision = 3)
brks <- classes$brks
brks <- round(brks, 2)
saveGIF({
for(i in c(1:nlayers(s))){
l <- levelplot(s[[i]], colorkey=list(at=brks, labels=c(as.character(brks))), margin=FALSE)
plot(l)
}
}, interval=0.2, movie.name="animation.gif")

classify raster stack with levelplot (RasterVis)

i have a raster stack of 7 rasters with quite varying data ranges and not all of the rasters adhere to quite the same range. (some are low value ranges, some much higher). Using the levelplot function with the stack, it plots nicely enough, eg:
r <- raster(ncol=10,nrow=10)
r[] <- sample(c(1:3),size=100,replace=T)
r1 <- raster(ncol=10,nrow=10)
r1[] <- sample(c(1:9),size=100,replace=T)
r2 <- raster(ncol=10,nrow=10)
r2[] <- sample(c(5:15),size=100,replace=T)
r3 <- raster(ncol=10,nrow=10)
r3[] <- sample(c(3:35),size=100,replace=T)
s <- stack(r,r1,r2,r3)
breaks <- 7
my.at <- round(seq(min(minValue(s)), max(maxValue(s)), length.out = breaks),digits=2)
myColorkey <- list(at=my.at,height=0.95, width=1, labels=list(at=my.at,cex=1.1))
cols <- (brewer.pal(length(my.at)-1, "YlGnBu"))
levelplot(s,at=my.at,col.regions=cols,colorkey = myColorkey)
As you can see, the images with the lower value data are one colour (Actually in my real data most of the plots are one colour as the data range is dominated by two latter rasters). Using the levelplot function, i would like to reclassify the entire raster stack, teasing out some patterns in the lower value rasters with some classes that i define and simply assign anything over value x (perhaps 10 in the sample data above) to be one colour.
the usual method of ratifying and setting levels will not work for a stack and any workaround i have tried (using a matrix and reclassify) will not force more levels than there are classes for a raster
this is my workaround, using the standard legend, but i'd like to use ratify etc if possible;
# using s from above
m <- c(0,1,1, 1,3,2, 3,6,3, 6,10,4, 10,35,5)
mat <- matrix(m, ncol=3, byrow=TRUE)
src <- reclassify(s, mat)
breaks <- nrow(mat)
my.at <- (0:breaks)
myColorkey <- list(at=my.at,height=0.95, width=1, labels=list(at=my.at+0.5,labels=c("0-1","1-3","3-6","6-10","10-35"),cex=1.1))
cols <- (brewer.pal(length(my.at)-1, "YlGnBu"))
levelplot(src,at=my.at,col.regions=cols,colorkey = myColorkey)

overlap points(or symbols) in a raster with levelplot

I would like to ask some help for plotting a matrix(converted to raster) and overlay with symbols another one. For that, I was trying to use layer (and sp.points), as in several examples that I have read...but I am not very familiar with that and I am missing something. This would be the main idea. I will put a reproducible example (since the real data are more complex).
#Create 1 matrix
m1 <- matrix(runif(100),nrow=10,ncol=20)
#create 2 matrix
m2 <- matrix(1:4,nrow=10,ncol=20)
#Convert to raster
M1<- stack(raster(m1))
#plot
p<-levelplot(M1, margin=FALSE)
#For the second matrix
xy<-melt(m2)
#Add the layer
p +layer(sp.points(xy, pch=1:4)
I am aware that this is wrong..but I don't know how to plot it...
Any suggestion will be appreciated.
Thanks in advance!
Here is a couple of ideas/alternatives that might be of use:
m1 <- matrix(runif(100),nrow=10,ncol=20)
m2 <- matrix(1:4,nrow=10,ncol=20)
library(raster)
M1 <- raster(m1)
M2 <- raster(m2)
plot(M1)
text(M2)
pts <- cbind(xyFromCell(M1, 1:ncell(M1)), value=as.vector(t(m2)))
plot(M1)
cols=rainbow(4)[pts[,3]]
points(pts)
points(pts, col=cols, pch=20)
xy <- SpatialPoints(pts[,1:2])
library(rasterVis)
p <-levelplot(M1, margin=FALSE)
p + layer(sp.points(xy, pch=1:4))
spplot(M1, sp.layout = list("sp.points", xy, pch=1:4))

ScatterPlot between two rasters, giving color from a third raster

I'm plotting two rasters data, producing the image below.
I'd like to color each point in the graph with a variable taken from a third raster data (with the same bbox, pixel size etc.).
Any ideas from R-Users? This operation is very easy in plotting data from a dataset, but I don’t know about raster…
Here I attach the code (simplified, I think you don't need all the plot parameters e.g. abline, xlab and so on) that produced the image:
plot(mask(raster1, my_mask,maskvalue=0), #first raster, masked by my_mask
mask(raster2, my_mask,maskvalue=0), #second raster, masked by my_mask
col = alpha('black', 0.1), #the current color scheme
)
raster3 #raster with categorical variable,
#that should give the colors to the points in the graph
Thanks a lot!
With the xyplot method defined in
rasterVis
you can use layers of a RasterStack as if they were columns of a
data.frame. Therefore, they can be the components of the formula or
the groups argument.
For example,
library(raster)
library(rasterVis)
f <- system.file("external/test.grd", package="raster")
r <- raster(f)
r2 <- r + 500 * init(r, rnorm)
## categorical variable
r3 <- cut(r, 3)
s <- stack(r, r2, r3)
names(s) <- c('r', 'r2', 'r3')
xyplot(r ~ r2, groups = r3, data = s,
auto.key = list(space = 'right'),
alpha = 1)

Resources