简体   繁体   中英

Plot "boolean" raster and add NA-Values to legend

I have a raster with values that are either 1 or NA . By default the plot(raster_1) -call gives me a continuous legend. What I actually want is a simple categorical legend with two entries and colors. One being 1 the other one NA . I converted my raster to a categorical object with as.factor(raster_1) . But now I don't know how I can generate this simple legend... My raster-values look like this:

source     : memory
names      : raster_1 
values     : 1, 1  (min, max)
attributes :
 ID
  1

Set legend=FALSE and colNA other than the default 'transparent' in the call to plot and then add a custom legend where you can set xpd=TRUE , so the legend can be placed outside the plot margins. inset = c(-0.3,0) can be adjusted to your preference in the call to legend

r <- raster(ncol=10, nrow=10, xmx=-80, xmn=-150, ymn=20, ymx=60) #toy raster
values(r) <- c(rep(1, 30), rep(NA, 30), rep(1, 40)) #add 1 and NA values
r
#class      : RasterLayer 
#dimensions : 10, 10, 100  (nrow, ncol, ncell)
#resolution : 7, 4  (x, y)
#extent     : -150, -80, 20, 60  (xmin, xmax, ymin, ymax)
#crs        : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0 
#source     : memory
#names      : layer 
#values     : 1, 1  (min, max)
plot(r, col='red', colNA='black', legend=FALSE)
legend('topright', legend = c('1', 'NA'), pch=15, col=c('red', 'black'), inset = c(-0.3,0), xpd = TRUE)

在此处输入图片说明

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