Reputation: 803
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)
Upvotes: 3
Views: 2630
Reputation: 47071
If you want to show all values you can use the text
method:
library(raster)
r <- raster(nrow=3, ncol=3, vals=1:9)
plot(r)
text(r)
For a subset, you can do something like:
z <- rasterToPoints(r, function(x) x > 6 )
plot(r)
text(z[,1], z[,2], z[,3])
Upvotes: 6
Reputation: 133
I know this question is already marked as answered, but building on Josh's solution and Eddie's follow-up question, here is a little for-loop that does what Eddie was asking for (plot raster values without decimal numbers and without using click
):
r <- raster(nrow=3, ncol=3)
r[] <- runif(ncell(r))
plot(r)
for(i in 1:ncell(r)){
xycoords <- xyFromCell(r, cell = i)
value <- extract(r, xycoords)
text(xycoords, labels = round(value))
}
Upvotes: 0
Reputation: 162321
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)
Upvotes: 5