Search code examples
plotrasterterra

plot raster and overlay point values that satisfy criteria


I am plotting a raster like this one:

library(terra)
set.seed(1)
rr <- rast(matrix(rnorm(400, 1.5, 1), nrow=20, ncol=20))
plot(rr)

What I would ideally like is to add points to the plot where the raster values are above a threshold, the points I would like are seen here:

plot(clamp(rr, lower=3))

In my mind, something like this is possible (but in reality, this didn't work)

plot(rr)
points(clamp(rr, lower=3))

or maybe

plot(rr)
points(rr[rr>3])

obviously my examples don't work... anyone got an idea?

thank you,

m


Solution

  • You can do

    library(terra)
    set.seed(1)
    rr <- rast(matrix(rnorm(400, 1.5, 1), nrow=20, ncol=20))
    x <- clamp(rr, lower=3, values=FALSE)
    
    plot(rr)
    points(as.points(x))
    lines(x)
    ## or polygons 
    # polys(as.polygons(x), dens=10)
    

    So while lines(x) works, points(x) does not (this has now been fixed in the development version).

    For this to work, the cells you do not want points for must be NA. Hence the values=FALSE in clamp.

    To show different values (or ranges) for each point you can use plot(..., add=TRUE)

    p <- as.points(x)
    plot(rr, plg=list(shrink=.3))
    plot(p, "lyr.1", add=T, legend=T)