Home > Software engineering >  How to plot a binary matrix without using additional packages?
How to plot a binary matrix without using additional packages?

Time:12-18

I created a binary matrix and I wanna plot 1's as black square.

How can I write it without using any package?

For example, my matrix is:

m <- matrix(c(0,1,1,0,0,1,0,1,1),nrow=3, ncol=3)

CodePudding user response:

Do you want this?

m <- matrix(c(0,1,1,0,0,1,0,1,1), nrow=3, ncol=3)

image(m, main = "My binary matrix plot", col = c("white", "black"))

enter image description here

CodePudding user response:

If image doesn't suffice, we could use write a generalized function using mapply.

chessplot <- function(m, col=1, border=NA) {
  stopifnot(!dim(m)[1] != dim(m)[2])  ## allows only square matrices
  n <- nrow(m)
  plot(n, n, type='n', xlim=c(0, n), ylim=c(0, n))
  mapply(\(i, j, m) {
    rect(-1   i, n - j , 0   i, n - j   1, col=m, border=border)
  }, seq(n), rep(seq(n), each=n), t(m)) |> invisible()
}

Gives:

chessplot(m3)

enter image description here

chessplot(m4)

enter image description here

chessplot(m8)

enter image description here


Data:

m3 <- structure(c(0, 1, 1, 0, 0, 1, 0, 1, 1), .Dim = c(3L, 3L))
m4 <- structure(c(0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0), .Dim = c(4L, 
4L))
m8 <- structure(c(0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 
1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 
0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 
0, 1, 0, 1, 0), .Dim = c(8L, 8L))
  • Related