在本书中,我提供了一个例子来解决这个问题。我的回答主要是该示例的一部分的副本。
因为您没有提供数据集来重现您的代码,所以我将使用书中提出的文件:
library(rasterVis)
setwd(tempdir())
myURL <-'https://github.com/oscarperpinan/spacetime-vis/raw/master/data/'
download.file(paste0(myURL,'SISav.grd'), 'SISav.grd', method = 'wget')
download.file(paste0(myURL,'SISav.gri'), 'SISav.gri', method = 'wget')
SISav <- raster('SISav')
下一行定义了发散的调色板:
meanRad <- cellStats(SISav, 'mean')
SISav <- SISav - meanRad
## Modify the palette with your colors
divPal <- brewer.pal(n=9, 'PuOr')
divPal[5] <- "#FFFFFF"
divTheme <- rasterTheme(region=divPal)
rng <- range(SISav[])
## Number of desired intervals
nInt <- 15
## Increment corresponding to the range and nInt
inc0 <- diff(rng)/nInt
## Number of intervals from the negative extreme to zero
n0 <- floor(abs(rng[1])/inc0)
## Update the increment adding 1/2 to position zero in the center of an interval
inc <- abs(rng[1])/(n0 + 1/2)
## Number of intervals from zero to the positive extreme
n1 <- ceiling((rng[2]/inc - 1/2) + 1)
## Collection of breaks
breaks <- seq(rng[1], by=inc, length= n0 + 1 + n1)
## Midpoints computed with the median of each interval
idx <- findInterval(SISav[], breaks, rightmost.closed=TRUE)
mids <- tapply(SISav[], idx, median)
## Maximum of the absolute value both limits
mx <- max(abs(breaks))
## Interpolating function that maps colors with [0, 1]
## rgb(divRamp(0.5), maxColorValue=255) gives "#FFFFFF" (white)
break2pal <- function(x, mx, pal){
## x = mx gives y = 1
## x = 0 gives y = 0.5
y <- 1/2*(x/mx + 1)
rgb(pal(y), maxColorValue=255)
}
divRamp <- colorRamp(divPal)
## Diverging palette where white is associated with the interval
## containing the zero
pal <- break2pal(mids, mx, divRamp)
最后levelplot
显示结果:
levelplot(SISav, par.settings=rasterTheme(region=pal),
at=breaks, contour=TRUE)