Search code examples
rplotselectioncellraster

Outline a raster cell of interest by cell number


I would like to outline a raster cell given the cell number in a plot. I have made a simplified example, that I was able to make in power point, but may have a resolution that will be more difficult to do this for (720 x 360 vs 3 x 5). To generate the sample data:

library(raster)
x = raster(matrix(seq(1,15), nrow = 3))
plot(x)

And I would like a modification to the plot command (preferably) so that if I were to select the 5th cell, the result looks something like this: enter image description here


Solution

  • Here's a general approach, where we plot an extent based on the row and column of the cell of interest.

    library(raster)
    r <- raster(matrix(1:15, nrow=3))
    plot(r)
    rc <- rowColFromCell(r, 5)
    plot(extent(r, rc[1], rc[1], rc[2],  rc[2]), add=TRUE, col='red', lwd=3)
    

    fig1

    The second through fourth arguments to extent determine the span of rows (args 2 and 3) and columns (args 4 and 5) that will be used to calculate the extent.

    If we wanted to outline cells 3, 4, 8, and 9, we could do:

    plot(r)
    rc <- rowColFromCell(r, c(3, 4, 8, 9))
    plot(extent(r, min(rc[, 1]), max(rc[, 1]), 
                min(rc[, 2]),  max(rc[, 2])), add=TRUE, col='red', lwd=3)
    

    fig2

    This works fine for rectangular extents around contiguous sets of cells. If you want to outline an arbitrary selection of cells, you could consider rasterToPolygons. E.g. for cells 2, 8, 9, 11, and 14:

    plot(r)
    r2 <- r
    r2[setdiff(seq_len(ncell(r2)), c(2, 8, 9, 11, 14))] <- NA
    r2[!is.na(r2)] <- 1
    plot(rasterToPolygons(r2, dissolve=TRUE), add=TRUE, border='red', lwd=2)
    

    Here, we create a copy of the raster, set all other cells to NA, and then the focal cells to a common value (1, in this case). rasterToPolygons then converts the non-NA cells to polygons, dissolving touching polys if desired.

    fig3