library(raster)
library(igraph) # need pipe for one example below
ras <- raster(matrix(c(0,0,1,2), ncol=2, nrow=2))
# Use replacement method
setColors(ras, n=3) <- c("red", "blue", "green")
if (interactive()) {
clearPlot()
Plot(ras)
}
# Use function method
ras <- setColors(ras, n=3, c("red", "blue", "yellow"))
if (interactive()) {
clearPlot()
Plot(ras)
}
# Using the wrong number of colors, e.g., here 2 provided,
# for a raster with 3 values... causes interpolation, which may be surprising
ras <- setColors(ras, c("red", "blue"))
if (interactive()) {
clearPlot()
Plot(ras)
}
# Real number rasters - interpolation is used
ras <- raster(matrix(runif(9), ncol=3, nrow=3)) %>%
setColors(c("red", "yellow")) # interpolates when real numbers, gives warning
if (interactive()) {
clearPlot()
Plot(ras)
}
# Factor rasters, can be contiguous (numerically) or not, in this case not:
ras <- raster(matrix(sample(c(1,3,6), size=9, replace=TRUE), ncol=3, nrow=3))
levels(ras) <- data.frame(ID=c(1,3,6), Names=c("red", "purple", "yellow"))
ras <- setColors(ras, n=3, c("red", "purple", "yellow"))
if (interactive()) {
clearPlot()
Plot(ras)
}
# if a factor rastere, and not enough labels are provided, then a warning
# will be given, and colors will be interpolated
# The level called purple is not purple, but interpolated betwen red and yellow
ras <- setColors(ras, c("red", "yellow"))
if (interactive()) {
clearPlot()
Plot(ras)
}
Run the code above in your browser using DataLab