Home > Back-end >  How to plot a raster from a numeric matrix with ``ggplot2``
How to plot a raster from a numeric matrix with ``ggplot2``

Time:05-04

I wish to create a facetted raster plot based on a numeric matrix. The facets are defined by rows in the matrix.

The following sample data represents all the ways a 2 x 1 cell shape (the "Shape") may be placed horizontally and vertically on a 3 x 3 grid.

m1 <- matrix(c(1,0,0,1,0,0,0,0,0,
               0,0,0,1,0,0,1,0,0,
               0,1,0,0,1,0,0,0,0,
               0,0,0,0,1,0,0,1,0,
               0,0,1,0,0,1,0,0,0,
               0,0,0,0,0,1,0,0,1,
               1,1,0,0,0,0,0,0,0,
               0,1,1,0,0,0,0,0,0,
               0,0,0,1,1,0,0,0,0,
               0,0,0,0,1,1,0,0,0,
               0,0,0,0,0,0,1,1,0,
               0,0,0,0,0,0,0,1,1), ncol = 9, byrow = TRUE)

Each row in the matrix represents a possible position for the Shape. Such that, formatting a row as a matrix with three columns will illustrate the position (1 = occupied cell and 0 = unoccupied cell).

matrix(m1[1,], ncol = 3, byrow = TRUE)
#>      [,1] [,2] [,3]
#> [1,]    1    0    0
#> [2,]    1    0    0
#> [3,]    0    0    0

Created on 2022-05-03 by the enter image description here

  • Related