Search code examples
rgraphicsmosaic-plot

Color each field in a mosaic plot in R


I have the following R-code:

mosaictable <- matrix (c(1/4*2/3, 3/4*2/3, 1/4*1/3, 3/4*1/3), ncol = 2)
rownames(mosaictable) <- c ("Gelb", "Nicht gelb")
colnames(mosaictable) <- c ("Gelb", "Nicht gelb")
mosaicplot((mosaictable), sub = "1. Zug", ylab = "2. Zug", color = c("gray60", "black", "white", "white"), las = 1, main = "Einheitsquadrat")

Unfortunately, my mosaic-plot only displays the colors "gray60" and "black" over multiple fields, but I want each field to be colored individually with the colors I've chosen. How can I achieve this? Thank you!

I tried to submit the color argument as matrix instead of a vector, but it didn't change anything. Any ideas?


Solution

  • You could use the mosaic function from the vcd package instead which makes it possible to define a matrix with colors so you can color each field in a mosaic plot like this:

    library(vcd)
    mosaic((mosaictable), 
           sub = "1. Zug", ylab = "2. Zug", 
           gp = gpar(fill = matrix(c("gray60", "black", "white", "white"), ncol = 2)), 
           las = 1, main = "Einheitsquadrat")
    

    Created on 2024-03-26 with reprex v2.0.2