简体   繁体   中英

base plot NA values in black color in raster map in R

I have a rasterized S4 object, created by using rasterize function onto a dataset. The dataset that had been put into it has some NA values. I would like to depict these NA cells in black color when using the base plot function in R.

Tried the following code:

library(RColorBrewer)

my.colors = colorRampPalette(rev(brewer.pal(9, "RdBu")))

plot(rasterized object, col= ifelse(is.na(rasterized object@data@values),"black", my.colors(255)), box=F, add=F)

# col(ifelse) was inspired from Plot conditional color with NA data

That doesn't work and many grid cells with real values get depicted in black instead.

There are no error messages.

What could be changed, given I want to use basic plot syntax of R and not ggplot ?

I guess that you are using the raster package and that the rasterized S4 object is a RasterLayer

If so, the plot function of the raster package (version 3.4.5) has a colNA argument.

plot(r, col = my.colors(255), colNA = "black")

Here is a reproducible example:

library(raster)
library(RColorBrewer)
r <- raster(nrows=10, ncols=10)
r <- setValues(r, c(rep(NA, 10), 1:90)) 

my.colors = colorRampPalette(rev(brewer.pal(9, "RdBu")))

plot(r, col = my.colors(255), colNA = "black")

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