This article is originally published at https://rcrastinate.blogspot.com/
Today I want to write about a solution to a quite specific problem. Suppose, you want to label cells in your 'vcd' package mosaic plots in a custom way. For example, we might want to use cell labels which indicate "too much" or "too few" cases (given your expected values). Such labels might be "+" and "-" (and maybe "++" and "--" for higher residuals).
We create our custom table:
tab <- rbind(c(450, 230), c(200, 600))We create our mosaic plot:
library(vcd)mosaic(tab, shade = T)So far, so good.
Now, we want to use custom labels for the cells.
Let's first create a second table containing our labels:
lab.tab <- rbind(c("++", "--"),
c("--", "++"))
Now, we use lab.tab in our call to mosaic():
mosaic(tab, labeling = labeling_cells(text = lab.tab))
We get this:
This is not what we wanted - only the first label in lab.tab is used. Bummer! Also, R throws some warnings at us (sorry, they're in German):
Warnmeldungen:
1: In if (!is.na(txt)) txt :
Bedingung hat Länge > 1 und nur das erste Element wird benutzt
2: In if (!is.na(txt)) txt :
Bedingung hat Länge > 1 und nur das erste Element wird benutzt
3: In if (!is.na(txt)) txt :
Bedingung hat Länge > 1 und nur das erste Element wird benutzt
4: In if (!is.na(txt)) txt :
Bedingung hat Länge > 1 und nur das erste Element wird benutzt
The solution is to give correct 'dimnames' to our custom tables:
dimnames(tab) <- list(VarA = c("levelA", "levelB"),
VarB = c("levelA", "levelB"))
dimnames(lab.tab) <- dimnames(tab)
Note, that we have to use named elements here for the dimnames-list (these names are "VarA" and "VarB" in the example)!
Now the warnings are gone and it works:
mosaic(tab, labeling = labeling_cells(text = lab.tab))
It took me some time to figure this out, because all the examples in ?mosaic, ?strucplot and ?labeling_cells already have a correct 'dimnames'-structure. Maybe, this helps someone...
Thanks for visiting r-craft.org
This article is originally published at https://rcrastinate.blogspot.com/
Please visit source website for post related comments.