Search code examples
rplotggplot2vcd

Mosaic plot/grid plot in black and white for dummies


I have a data set consisting of dummies, which looks like follows:

# Example data
set.seed(123)
data <- data.frame(x1 = rbinom(10, 1, 0.3),
                   x2 = rbinom(10, 1, 0.6),
                   x3 = rbinom(10, 1, 0.5))

I want to create a mosaic plot/grid plot (actually I am not sure how such a plot should be called), in which each 1-value is displayed in black and each 0-value is displayed in white. There should be no white space or any other color between the displayed lines.

An example of a plot I would like to create could be found in this paper on page 97:

enter image description here

I tried several different packages like ggplot2 or vcd, but unfortunately I was not able to produce exactly the same plot. Any help or any hint for a package is highly appreciated!


Solution

  • The image function is perhaps the easiest way to display matrices with colors. You need to transpose and reverse it to have the order correct

    image(t(as.matrix(data[nrow(data):1, ])), col = c(0, 1), axes = FALSE)
    axis(1, seq(0, 1, l = ncol(data)), seq_len(ncol(data)))
    axis(2, seq(0, 1, l = nrow(data)), seq_len(nrow(data)))
    legend(1.1, 0, c(0:1), fill = c(0, 1), xpd = TRUE)
    

    enter image description here