34

I have an elevation model plotted in R

r <- raster("example.dem")
plot(r, col = topo.colors(20))

Elevation plot

Some of the values are below sea level (0), and I'd like to have those display in red. How can I assign specific ranges to specific colours in the plot()?

Simbamangu
  • 14,773
  • 6
  • 59
  • 93

1 Answers1

37

Here is a really simple example

library(raster)
data(volcano)
volcanoR <- raster(volcano)

#making colors below 100 red and above 180 blue in this example

breakpoints <- c(94,100,120,140,160,180,195)
colors <- c("red","white","white","white","white","blue")
plot(volcanoR,breaks=breakpoints,col=colors)

enter image description here

You just need to pass the plot a vector of break points and a vector of colors to match the breakpoints. Check out the RColorbrewer package for some very nice built in color ramps. Also check out the classInt package for making the breakpoints.

Andy W
  • 4,234
  • 5
  • 45
  • 69
  • Excellent- embarrassing how long I fiddled with this. Is there a straightforward way to import colour ramps from colour brewer? EDIT: sorry, I now see you're referring to a package, not the site! – Simbamangu Nov 29 '11 at 13:25
  • 3
    @Simbamangu, We have all been there. I actually find many of the examples of doing this obfuscate what is actually being passed as breakpoints and colors by using objects created from other packages (like the ones I suggest). I think it is simplest to see it like this, and then go on to use the other packages to create appropriate breakpoints and color ramps without doing so much work. – Andy W Nov 29 '11 at 13:28
  • 4
    I completely agree with that - the examples in many of the R packages are really tough to figure out, with too much carried through from other objects! – Simbamangu Nov 30 '11 at 06:39
  • What if you want to specify the colors of certain values, instead of intervals? – Rodrigo Apr 26 '21 at 23:08
  • If you want the legend to look the same @Rodrigo, you can just make the interval very small and cover the value of interest. If you want to plot categories instead of continuous, see https://stackoverflow.com/a/19139384/604456 for an example. (Or you could use other plotting libraries, like ggplot.) – Andy W Apr 27 '21 at 12:20
  • Yes, I was thinking of categories. The linked answer doesn't always work. If there are only sparse values (ex: 1, 2, 5, 8, 14) or maybe for a different reason (the order in which the values appear on the raster?) the colors get mapped wrong. I used image to solve this, but I thought that plot should do it, too. – Rodrigo Apr 27 '21 at 15:40