【问题标题】:How to plot a binary matrix without using additional packages?如何在不使用附加包的情况下绘制二进制矩阵?
【发布时间】:2022-01-20 22:52:37
【问题描述】:

我创建了一个二进制矩阵,我想将 1 绘制为黑色方块。

如何在不使用任何包的情况下编写它?

比如我的矩阵是:

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

【问题讨论】:

    标签: r matrix plot package


    【解决方案1】:

    你想要这个吗?

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

    【讨论】:

    • 非常简洁,不仅适用于方阵,+1!我的答案的棋盘实际上只需要image(m8, col=0:1)。顺便说一句,我们也可以用image(t(m))“重新转置”矩阵。
    • @jay.sf 但我们不知道image 是如何工作的。也许,你的功能更快?
    【解决方案2】:

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

    【讨论】:

    • 你提出了一个更酷的解决方案,比我“+1”;)
    • plot(n, n, type='n',... 第一个 n 和第二个 n 是什么?
    • @manro n 用于行数。 type='n' 中的 'n' 创建一个空的plot,试试plot(1:3, type='n')。另见?plot.default。
    • 是的,NxN + 空图。纯 R 语言可用于加密))当您是新手时,很难将您的视图调整为阅读)
    • 赞成,但为什么要在stopifnot 中两次否定?
    猜你喜欢
    • 2020-10-22
    • 1970-01-01
    • 2019-01-15
    • 1970-01-01
    • 2022-10-15
    • 2010-12-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多