Search code examples
rraster

Unable to specify legend placement


I am making a plot of a map from a raster file. I would like my legend to be inside the plot itself instead of outside by default. I am using this code:

library(raster)
library(rgdal)
library(classInt)

NDII = raster("G:\\Sheyenne\\image_differencing\\NDII\\differenced.tif")
value.vector = round(values(NDII),2)
breaks.qt = classIntervals(value.vector, n = 3, style = "quantile", intervalClosure = "right")
breaks.qt = breaks.qt$brks
breaks.qt[2] = 0
xlim = c(616768.4, 646426)
ylim = c(5130933, 5159682)
print (plot(NDII, main="NDII", breaks=breaks.qt, col = rainbow(3), axes=F, xlim=xlim, ylim=ylim))
legend("topright")

but this returns:

enter image description here


Solution

  • Here is a reproducible example

    Example with binary data

    r <- raster(nrows = 50, ncols = 50)
    set.seed(123)
    id <- sample(1:2500, 100, replace = FALSE)
    r[id] <- 1
    plot(r)
    

    enter image description here

    Now with legend = FALSE and adding the legend after

    plot(r, legend = FALSE, col = rev(terrain.colors(2)))
    legend("topright", legend = c("Absence", "Presence"), fill = rev(terrain.colors(2)))
    

    enter image description here

    Example with continuous data

    r <- raster(nrows=10, ncols=10)
    r <- setValues(r, 1:ncell(r))
    
    
    plot(r, legend = FALSE, col = rev(terrain.colors(5)))
    legend("topright", fill = rev(terrain.colors(5)),  legend = c("0", "20", "40", "60", "80", "100"))
    

    enter image description here