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

July 29, 2016
By

(This article was first published on Rcrastinate, and kindly contributed to R-bloggers)

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”))
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 on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Sponsors

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)