How to label raster values in plot?

r, r-raster

Solution

Try the following, which is based on pieces cobbled together from the function returned by `getMethod("click", signature="Raster")`.

myClick <- function(x, n = Inf, id = FALSE, xy = FALSE, cell = FALSE, 
                    type = "n", show = TRUE, ...) {
    i <- 0
    n <- max(n, 1)
    while (i < n) {
        i <- i + 1
        loc <- locator(1, type, ...)
        xyCoords <- cbind(x = loc$x, y = loc$y)
        cells <- na.omit(cellFromXY(x, xyCoords))
        if (length(cells) == 0)
              break
        value <- extract(x, cells)
        text(xyCoords, labels = value)
    }
}

## Try it out
myClick(r, n=4)

Problem

How could I add pixel values to the plot? I can get the values by using `click()` but I want it to appear in the plot. ``` library(raster) r <- raster(nrow=3, ncol=3) r[] <- 1:ncell(r) plot(r) click(r) ```

Original source