R 使用levelplot指定二进制数据的颜色

R 使用levelplot指定二进制数据的颜色,r,matrix,binary,levelplot,R,Matrix,Binary,Levelplot,我有二进制编码的光栅数据,我想使用rasterVis包中的levelplot来绘制数据,这样0个值为绿色,1个值为红色。我似乎找不到如何为值指定颜色 例如, # 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") levelp

我有二进制编码的光栅数据,我想使用
rasterVis
包中的
levelplot
来绘制数据,这样0个值为绿色,1个值为红色。我似乎找不到如何为值指定颜色

例如,

# 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)
#创建一个0和1的矩阵

nr您必须使用
批准
将您的
光栅
数据声明为分类变量(请参阅):

库(rasterVis)

nr
levelplot
不是基本R的一部分。请在问题中提及您正在使用的程序包名称。@lmo刚刚添加了它,但我目前无法访问此程序包,因此我无法测试任何内容,但您可以使用
ifelse
尝试一些东西。可能是col=
ifelse(0,“绿色”、“红色”)
。无论如何,这项技术适用于基本R图。查看帮助部分:
?levelplot
,查看是否手动调整颜色类型。
m2 <- matrix(0, nr, nc)
levelplot(m2, col.regions=colour, margin = FALSE)
m3 <- matrix(1, nr, nc)
levelplot(m3, col.regions=colour, margin = FALSE)
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)