简体   繁体   中英

Raster color - positive red & negative blue

I have a spatial raster create in R with positive and negative values. I want for all positive values a red color ramp and for all negative values a blue color ramp. Basically I want to define my own color ramp with zero as blank, positive values in red, and negative values in blue (these can be any colors). Most color ramps in R spread all available colors between the min. and max. value.

I do not seem to be able to find the solution, so hopefully someone here has suggestions.

Here's an example for a raster with values between -5 and 5 for which I need a 'new' col definition:

library(raster)
set.seed(9)
r <- raster(ncol=10, nrow=10)
r1 <- setValues(r, (1:ncell(r))/10 + rnorm(ncell(r)) - 5)
plot(r1, col= topo.colors(12))

Best -- Niels

I could not find a more elegant way than adding a tolerance, because colours should be given to a segment not a single point (eg 0) if you get a more elegant way, please go ahead

library(raster)
set.seed(9)
r <- raster(ncol=10, nrow=10)
r1 <- setValues(r, (1:ncell(r))/10 + rnorm(ncell(r)) - 5)
tol=10^-12
breakpoints <- c(min(as.data.frame(r1)),0-tol,0+tol,max(as.data.frame(r1)))
colors <- c("blue","white","red")
r1.range <- c(minValue(r1), maxValue(r1))
plot(r1,breaks=breakpoints,col=colors,     axis.args=list(at=c(r1.range[1], 0,r1.range[2])))

The axis.args argument is only needed to make the legend look nice, you can take it away if it looks scary to you.

这个

Source:

https://gis.stackexchange.com/questions/17339/raster-legend-in-r-how-to-colour-specific-values

should solve your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM