简体   繁体   中英

Plotting a raster in R with specific colors for specific values

I hava a raster with 10 values:

vals <- c(1,2,3,4,5,12,123,1234,12345,23,234,2345,34,345,45)

I would like to produce a plot, where value 1 to 5 is coloured. And all other values are in grey scale. Plus, I'd like the legend to specifically show each value and the corresponding color. In ArcGIS this is easy to accomplish (see desired outcome) 在此处输入图片说明

I tried a lot, but I could not come up with a solution to get a good result. Can anyone help?

Raster can be found here: https://www.dropbox.com/s/kzcba9r4t9z4mc1/raster.tif?dl=0

Edit:

Turns out, the base plotting is a bit annoying with categorical data. I'm sure there's a way, but why take the rocky road if there's a highway.

The great package rasterVis makes it easy to plot categorical rasters ... and many more things for that matter. Check out the homepage for all the functionality.

Back to your problem:

library(raster)
library(rasterVis)

#load raster
r <- raster('raster.tif')

#define color palette
cpal <- c('darkred','orange','green','dodgerblue','navy',grey.colors(8,start = 0.4,end=0))

#make categorical
r2 <- ratify(r)

#plot
levelplot(r2,col.regions=cpal,att='ID')

And the result:

在此处输入图片说明

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