Extract the results plotted in the margin of the levelplot function - r

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')

Related

r raster statistics per grid cell zone

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.

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")

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)

In levelplot (RasterVis), what by default does the graph show on each axis?

I'm using the levelplot function in the RasterVis package to plot one raster. I use the following code on my GeoTiff:
require(raster)
require(rasterVis)
data <- raster("mytiff.tif")
levelplot(data, layers=1, par.settings=RdBuTheme)
What, by default, do the graphs presented in the margins show? Is it the mean for each column/row or the median or a cumulative count or something else?
I can't find this in the help information, so any enlightenment would be much appreciated.
Thanks!
These graphics are the row and column summaries of the
RasterLayer. The summary is computed with the function defined by
FUN.margin (which uses mean as default value).
Let's illustrate it with an example:
library(raster)
library(rasterVis)
f <- system.file("external/test.grd", package="raster")
r <- raster(f)
levelplot(r)
The graphics shown in the margins can be produced with the zonal
function. With init we create two RasterLayer with the rows and
cols numbers to define the zones to be summarized.
rows <- init(r, v='row')
cols <- init(r, v='col')
rAvg <- zonal(r, rows, fun='mean')
cAvg <- zonal(r, cols, fun='mean')
The result is the same:
plot(rAvg, type='l')
plot(cAvg, type='l')

Resources