Eddie - 1 year ago 122

R Question

How could I add pixel values to the plot? I can get the values by using

`click()`

`library(raster)`

r <- raster(nrow=3, ncol=3)

r[] <- 1:ncell(r)

plot(r)

click(r)

Answer Source

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)
```