【发布时间】:2022-01-20 22:52:37
【问题描述】:
我创建了一个二进制矩阵,我想将 1 绘制为黑色方块。
如何在不使用任何包的情况下编写它?
比如我的矩阵是:
m <- matrix(c(0,1,1,0,0,1,0,1,1),nrow=3, ncol=3)
【问题讨论】:
我创建了一个二进制矩阵,我想将 1 绘制为黑色方块。
如何在不使用任何包的情况下编写它?
比如我的矩阵是:
m <- matrix(c(0,1,1,0,0,1,0,1,1),nrow=3, ncol=3)
【问题讨论】:
如果image 不够用,我们可以像这样使用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()
}
chessplot(m3)
chessplot(m4)
chessplot(m8)
数据:
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))
【讨论】:
plot(n, n, type='n',... 第一个 n 和第二个 n 是什么?
n 用于行数。 type='n' 中的 'n' 创建一个空的plot,试试plot(1:3, type='n')。另见?plot.default。
stopifnot 中两次否定?