简体   繁体   中英

Mosaic Plot Help in R

My current plot: 在此处输入图片说明 My desired plot (nevermind the variables s)

在此处输入图片说明

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)

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)

默认脊椎图

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)

自定义脊椎图

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM