tuannaorhaner
tuannaorhaner

Reputation: 11

How to plot a binary matrix without using additional packages?

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)

Upvotes: 1

Views: 162

Answers (2)

jay.sf
jay.sf

Reputation: 73272

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

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))

Upvotes: 2

manro
manro

Reputation: 3677

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

Upvotes: 2

Related Questions