1
votes

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

1
what software are you using?NKN
Your question seems vague. Could you explain in more detail? A picture would help.marsze
@NKN he said he was using R.Irene
@Niels Raes if the solution is useful for you, consider marking the tick on it, otherwise let me know if I can helpIrene

1 Answers

0
votes

I could not find a more elegant way than adding a tolerance, because colours should be given to a segment not a single point (e.g. 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.

this

Source:

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

should solve your problem.