문제

I've classified lots of rasters and I'd like to write them with the symbology I've defined.

Here is the kind of raster I'm dealing with:

library(raster)
library(rasterVis)
r <- raster(nrow=10, ncol=10)
r[] = 1
r[51:100] = 3
r[3:6, 1:5] = 5
r <- ratify(r)

rat <- levels(r)[[1]]
rat$landcover <- c('Pine', 'Oak', 'Meadow')
rat$class <- c('A1', 'B2', 'C3')
levels(r) <- rat
levelplot(r, col.regions=c('palegreen', 'midnightblue', 'indianred1'))
도움이 되었습니까?

해결책 2

I found the solution on this awesome website

addColorTable <- function(inRstName, outRstName, rat.df){
  library(rgdal)
  r<- readGDAL(inRstName)
  rat.df$color<- as.character(rat.df$color)
  rat.df$attribute<- as.character(rat.df$attribute)
  outRst <- writeGDAL(r, outRstName, type="Byte", 
  colorTable=list(rat.df$color), 
  catNames=list(rat.df$attribute), mvFlag=11L)
  return(raster(outRst))
}


library(rgdal)
library(raster)

# create dummy data set
r <- raster(nrow=10, ncol=10)
r[] <- 0
r[51:100] <- 1
r[3:6, 1:5] <- 2
r[1, 1] <- 3
writeRaster(r,'dummy_raster.tif',overwrite=T)

# This defines the values, the color and the attribute
valT <- c(0,1,2,3)
colT <-  c("#FF0000", "#FF9900" ,"#99FF00","#0000FF")
attT <- c('Forest','Water body','City','Cropland')
rat.df <- data.frame(value=valT,color=colT,attribute=attT)

# apply the magic function
rnew <- addColorTable('dummy_raster.tif', 'dummy_raster_with_symbology.tif', rat.df)

# plot the results and tadaaaa
spplot(rnew, col.regions=colT)

다른 팁

You can do this with raster version 2.3-40 or higher. Note that the classes should be sequential from 0,1,2,...

library(raster)
library(rasterVis)
r <- raster(nrow=10, ncol=10)
r[] = 0
r[51:100] = 1
r[3:6, 1:5] = 2
r <- ratify(r)

rat <- levels(r)[[1]]
rat$landcover <- c('Pine', 'Oak', 'Meadow')
rat$class <- c('A1', 'B2', 'C3')
levels(r) <- rat

x <- writeRaster(r, 'test.tif', overwrite=TRUE)
levelplot(x, col.regions=c('palegreen', 'midnightblue', 'indianred1'))
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top