Troubles with cell labels in mosaic plots… and how to solve them.

[This article was first published on Rcrastinate, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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…

To leave a comment for the author, please follow the link and comment on their blog: Rcrastinate.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)