Skip to contents

A Mosaic starts with a table of counts or a data frame of observations. Each split divides a rectangle among the levels of the next variable. With zero gaps, the area of a leaf is exactly its observed count divided by the total. With gaps, read shares from the split boundaries or the displayed values. Small cells may have too little physical room for a label.

library(ggplot2)
library(ggforma)
eyes <- marginSums(HairEyeColor, c("Hair", "Eye"))
ggmosaic(eyes, gap = 0, labeling = "border", label = NULL) +
  labs(title = "Hair and eye colour in 592 students")

Model and residuals

The Pearson residual is observed minus expected, divided by the square root of expected. The default independence model uses the table margins. A positive residual indicates more observations than the model predicts. The hcl display uses signed bands. Fixed breaks of 2 and 4 describe their size. To calibrate a fixed-margin null, explicitly simulate with mosaic_max_test() and pass its result to shade. Inspect its assumptions in the function reference.

ggmosaic(eyes, shade = "hcl", cuts = c(2, 4), labeling = "border", label = NULL)

cells <- mosaic_layout(eyes, gap = 0)$cells
head(cells[c("observed", "expected", "residual")])
  observed  expected    residual
1       68  40.13514  4.39839852
2      119 106.28378  1.23345810
3       26  26.38514 -0.07497794
4        7  47.19595 -5.85099741
5       20  39.22297 -3.06937747
6       84 103.86824 -1.94947682

More than two variables

Variable order controls which partitions appear first. A three-way table can be drawn directly. A conditioning formula creates separate views for the conditioning variable. Interpret each view with the chosen model scope. A matrix uses separate pair panels built by the same statistical engine.

ggmosaic(HairEyeColor, labeling = "border", label = NULL)

ggmosaic(Admit ~ Gender | Dept, data = UCBAdmissions, labeling = "border",
         label = NULL)

ggmosaic_pairs(HairEyeColor, upper = "pairwise", lower = "conditional")

Use raw source IDs for the category variables. Supply frequency counts as weights for aggregated data. Complex survey weights need their own variance and model assumptions. A structural zero represents an impossible combination; an observed zero can be an ordinary sampling outcome.