Mosaic Plot Help in R

2.1k views Asked by At

My current plot: enter image description here My desired plot (nevermind the variables s)

enter image description here

Specifically: explanatory variables on the bottom with an x-axis, response variables on the right, relative frequency and the y-axis on the left. I'll attach my R code below.

mosaictable <- matrix (c (3, 9, 22, 21), byrow = T, ncol = 2)
rownames (mosaictable) = c ("White", "Blue ")
colnames (mosaictable) = c ("Captured", "Not Captured")
mosaicplot  ((mosaictable), sub = "Pigeon Color", ylab = "Relative frequency", 
            col = c ("firebrick", "goldenrod1"), font = 2, main = "Mosaic Plot of Pigeon Color and Their Capture Rate"
            
            )
axis (1)
axis (4)
1

There are 1 answers

0
Achim Zeileis On

This particular flavor of mosaic display where you have a "dependent" variable on the y-axis and want to add corresponding annotation, is sometimes also called a "spine plot". R implements this in the spineplot() function. Also plot(y ~ x) internally calls spineplot() when both y and x are categorical.

In your case, spineplot() does almost everything you want automatically provided that you supply it with a nicely formatted "table" object:

tab <- as.table(matrix(c(3, 22, 9, 21), ncol = 2))
dimnames(tab) <- list(
  "Pigeon Color" = c("White", "Blue"),
  "Relative Frequency" = c("Captured", "Not Captured")
)
tab
##             Relative Frequency
## Pigeon Color Captured Not Captured
##        White        3            9
##        Blue        22           21

And then you get:

spineplot(tab)

default spine plot

Personally, I would leave it at that. But if it is really important to switch the axis labels from left to right and vice versa, then you can do so by first suppressing axes = FALSE and then adding them manually afterwards. The coordinates for that need to be obtained from the marginal distribution of the first variable and the conditional distribution of the second variable given the first, respectively

x <- prop.table(margin.table(tab, 1))
y <- prop.table(tab, 1)[2, ]
spineplot(tab, col = c("firebrick", "goldenrod1"), axes = FALSE)
axis(1, at = c(0, x[1]) + x/2, labels = rownames(tab), tick = FALSE)
axis(2)
axis(4, at = c(0, y[1]) + y/2, labels = colnames(tab), tick = FALSE)

customized spine plot