I have raster data that is coded in binary, and I would like to use the levelplot
in the rasterVis
package to plot the data, such that 0 values are green and 1 values are red. I can't seem to find how to specify a colour for a value.
As an example,
# create a matrix with 0s and 1s
nr <- 21
nc <- 11
m <- matrix(sample(0:1, nr*nc, replace=TRUE), nr, nc)
# plot the matrix
colour <- c("green", "red")
levelplot(m, col.regions=colour, margin = FALSE)
Which works fine, and produces this Binary matrix
But if I have matrices that happen to be all 0, or all 1,
m2 <- matrix(0, nr, nc)
levelplot(m2, col.regions=colour, margin = FALSE)
m3 <- matrix(1, nr, nc)
levelplot(m3, col.regions=colour, margin = FALSE)
I get the same plot, when what I want is for 0 values to be green and 1 values to be red.
Matrix with only 0 or 1 values
How do I specify such that if it's 0, it comes out green, and if it's 1, it comes out red?
You have to use ratify
to declare your raster
data as a categorical variable (see this example):
library(rasterVis)
nr <- 21
nc <- 11
m <- matrix(sample(c(0, 1), nr * nc, replace=TRUE), nr, nc)
r <- raster(m)
r <- ratify(r)
rat <- levels(r)[[1]]
rat$code <- c(0, 1)
levels(r) <- rat
levelplot(r)