overlap points(or symbols) in a raster with levelplot - r

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

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.

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)

plotting 3d with akima: z scale is not in accordance with real data

I have a matrix with 3 columns. I want to make a 3d plot to see the relation between these 3 parameters.
I used akima package in R
library(fields)
library(akima)
library(lattice)
data <- read.table("data.txt", header=F)
colnames(data) <- c("A","B","C") ###A would be x, B:y and C:z
reggrid <- interp(data$A,data$B,data$C,linear=T,extrap=F,duplicate="mean")
par(family="arial", cex=1.2)
x.ticks <- round(reggrid$x[seq(1,length(reggrid$x),length=5)],5)
y.ticks <- round(reggrid$y[seq(1,length(reggrid$y),length=5)],5)
wireframe( reggrid$z,
xlab=list("A",rot=-30),
ylab=list("B",rot=35),
zlab=list("C",rot=0),zlim=c(0,1),
scales=list(x=list(labels=x.ticks),
y=list(labels=y.ticks),arrows=F),
col.regions=rainbow(1000),
drape=T,
#shade=T,
colorkey=T,
screen=list(z=-20, x=-60, y=0))
the problem is that, while the real range of C is between 0-1, in the figures it is between 0.5-0.6!
Would you please help me how to solve this issue?

Make histograms of stacked rectangles rather than columns

With the following code, I get a histogram as below
x <- rnorm(100)
hist(x,col="gray")
What can I do to get to display the bars as stacked rectangles (visible by their outlines, rather than a change in fill color) instead of uniform columns? Each rectangle represents a frequency of, for example, 1, although I want to be able to change this through a parameter.
From answer at this question (h/t Vincent Zoonekynd).
x <- rnorm(100)
hist(x,col="gray")
abline(h=seq(5,40,5),col="white")
Here is a function to get you started (it is actually a modicication of part of the examples for the tkBrush function in the TeachingDemos package):
rechist <- function(x,...){
tmp <- hist(x,plot=F)
br <- tmp$breaks
w <- as.numeric(cut(x,br,include.lowest=TRUE))
sy <- unlist(lapply(tmp$counts,function(x)seq(length=x)))
my <- max(sy)
sy <- sy/my
my <- 1/my
sy <- sy[order(order(x))]
plot.new()
plot.window(xlim=range(br), ylim=c(0,1))
rect(br[w], sy-my, br[w+1], sy,
border=TRUE, col='grey')
rect(br[-length(br)], 0, br[-1], tmp$counts*my)
axis(1)
}
rechist( iris$Petal.Length )

Resources