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:
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)
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)
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.
This code should do what you want.
plot(raster(matrix(seq(1,15), nrow = 3)))
gridx = 5
gridy = 3
dx = 1/gridx #resolution of the grid
dy = 1/gridy
# if you want to specify the cell number (cell 1 is bottom left):
cell = 15
ny = floor(cell/gridx - dx)+1
nx = cell-gridx*(ny-1)
# if you want to give cell positions, just edit nx, ny
x1 = c(nx-1,nx-1,nx-1,nx)*dx
y1 = c(ny-1,ny,ny-1,ny-1)*dy
x2 = c(nx,nx,nx-1,nx)*dx
y2 = c(ny-1,ny,ny,ny)*dy
segments(x1,y1,x2,y2,col=2,lwd=2)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With