Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
460 views
in Technique[技术] by (71.8m points)

r - How to build a crossword-like plot for a boolean matrix

I have a boolean matrix:

mm <- structure(c(TRUE, TRUE, TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, 
                  FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, TRUE, 
                  FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, 
                  FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, 
                  FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, 
                  FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, 
                  TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, 
                  TRUE, TRUE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, 
                  TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, 
                  TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, 
                  TRUE, TRUE, TRUE), .Dim = c(10L, 10L), .Dimnames = list(NULL, 
                                                                          c("n1", "n2", "n3", "n4", "n5", "n1.1", "n2.1", "n3.1", "n4.1", 
                                                                            "n5.1")))

For this matrix, I'd like to make a plot similar to this one:

crossword-like plot

(the picture was taken from a similar question for Matlab: How can I display a 2D binary matrix as a black & white plot?)

Maybe I'm missing something obvious, but I don't see an easy way how to do that in R. So far, my best attempt is based on barplot:

m1 <- matrix(TRUE,ncol=10,nrow=10)
barplot(m1,col=mm)

but it makes all rows have the same colors.

Any ideas are welcome

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can do this using ggplot2's geom_tile and reshape2's melt:

library(ggplot2)
library(reshape2)

melted <- melt(mm)
ggplot(melted, aes(x = Var2, y = Var1, fill = value)) + geom_tile() +
    scale_fill_manual(values = c("white", "black"))

To make it a bit neater, you could remove the legend and the gray edges with some adjustments to the theme:

ggplot(melted, aes(x = Var2, y = Var1, fill = value)) + geom_tile() +
    scale_fill_manual(values = c("white", "black")) +
    theme_bw() +
    theme(legend.position = "none")

Final output:

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...