Use animate() with series of levelplots in R raster - r

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

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

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.

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)

How to plot and animate coordinates (latitude/longitude) data in R?

I have 10 lat and long points. With the code below, I can plot the coordinates, draw arrows in the order of their sequence and out-put a gif file that shows navigation order.
So far I was able to do this only with plot {graphics} function. because arrow {graphics} and saveGIF{animation} only seems to work with the plot function. I am wondering if its possible to this a more appropriate library such as ggmap (edit: I had mistakenly said ggplot), googleVis and etc.
library(graphics)
library(animation)
lat <- c(34.083398,34.072467,34.030237,34.597334,34.587142,34.488386,33.443484,33.946902,33.062739,32.273711,32.272611)
lon <- c(-107.907107,-106.893156,-107.971542,-105.225107,-105.13397,-103.196355,-104.52479,-103.655698,-106.0156,-107.71744,-107.713977)
coords = data.frame(lat,lon)
x <- coords$lat ; y <- coords$lon
s <- seq(length(x)-1) # one shorter than data
saveGIF({
for(s in 1:length(x)){
plot(x,y)
arrows(x[s], y[s], x[s+1], y[s+1], col = 1:s)
}
})
Yes, just remember to wrap your ggplot calls in print so they produce output. Toy example:
data=data.frame(i=1:100,x=runif(100),y=runif(100))
saveGIF({for(i in 2:100){print(ggplot(data[1:i,],aes(x=x,y=y))+geom_point())}})
Just write your code to produce each frame with ggplot2 functions and wrap in print. What did you try?

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