Skip to contents
library(ggmosaic2)
hec <- as.data.frame(HairEyeColor)
theme_set(theme_mosaic(base_size = 12))

The idea: pressure and energy

Friendly (1995, 1998), following Sall (1991), gives categorical data a physical model. Take the 71 people with red hair in HairEyeColor and think of them as molecules of an ideal gas in a cylinder of height 1, closed by a movable piston. A chamber of height 1 stands for probability 1: if everyone had red hair, seeing one more red-haired person would tell us nothing, and the gas is at ambient pressure, with no force on the piston.

If the probability of red hair is p, the same 71 molecules are squeezed into a chamber of height p. By Boyle’s law (pressure × volume is constant) the pressure is proportional to 1/p, and we see pressure as observation density: the number of points per unit area.

Compressing the gas takes work. Pushing the piston from height 1 down to p takes energy ∫ₚ¹ (1/h) dh = −log p for each observation, so the energy stored in a chamber of n observations at height p is −n log p: energy is negative log-likelihood.

Fitting = minimum energy, subject to constraints

Now stack the chambers for all four hair colours in one cylinder of height 1, with movable partitions between them. The top and bottom are fixed, which makes the probabilities sum to 1. The observations push on the partitions, which move until the forces balance: the pressure, seen as point density, is the same in every chamber. That happens when each chamber has height pᵢ = nᵢ/n, the maximum-likelihood estimate, and then the total energy −Σ nᵢ log pᵢ is as small as it can be. The likelihood equations are exactly the conditions for the forces to balance, and the number of movable partitions is the degrees of freedom.

In general, fitting a model means moving to the state of minimum energy allowed by the model’s constraints. A loglinear model is a set of constraints on where the partitions may go: cell areas must be proportional to the frequencies it can fit. Where the constraints hold partitions away from balance, some chambers are crowded (more observations than the model allows: high pressure, positive residuals) and others are sparse (low pressure, negative residuals). The extra energy needed to hold the partitions there, compared with letting them settle freely (the saturated model, where areas equal the observed counts), is half the likelihood-ratio statistic: G² = 2 Σ nᵢ log(nᵢ/mᵢ), where the mᵢ are the fitted frequencies.

In ggmosaic2:

  • area = "expected" draws the partitions where the model holds them,
  • jitter = TRUE puts one point per observation in each chamber, so the pressure shows as point density,
  • expected = names the model: a loglm()-style formula, by variable name or position (~ Hair + Eye or ~ 1 + 2), a shortcut ("independence", "conditional", "saturated", "equal"), or a table of expected frequencies,
  • residual shading and outlines show the pressure directly.

One-way table: equal probabilities

Observed: the partitions are free, and settle where the counts put them, with equal point density in every chamber (Friendly, 1995, fig. 3).

ggplot(hec, aes(x = product(Hair), weight = Freq)) +
  geom_mosaic(aes(fill = Hair), alpha = 0.15, jitter = TRUE, seed = 1995,
              divider = "vspine") +
  labs(title = "Observed: partitions in balance, minimum energy") +
  theme(legend.position = "none", axis.text.x = element_blank())

H₀: π₁ = π₂ = π₃ = π₄ (expected = "equal") is the constraint that holds the four chambers at equal size. Brown is crowded, Red and Blond are sparse, and holding them there takes extra energy: G² = 165.6 on 3 df.

As in MASS::loglm() and vcd::mosaic(), a formula ~ 1 means the first variable, Hair, which for a one-way table is the saturated model. Equal probabilities have no loglm() formula, hence the "equal" shortcut.

ggplot(hec, aes(x = product(Hair), weight = Freq)) +
  geom_mosaic(expected = "equal", area = "expected", jitter = TRUE,
              jitter_colour = "black", seed = 1995, divider = "vspine") +
  scale_fill_residual() +
  labs(title = "H0: equal probabilities") +
  theme(axis.text.x = element_blank())

Two-way table: independence

In product(Hair, Eye), Eye is the first (outer) split, the columns, and Hair the second, the rows. With the default jitter_shape = "first", the point symbols follow the first variable in product(), Hair.

ggplot(hec, aes(x = product(Hair, Eye), weight = Freq)) +
  geom_mosaic(aes(fill = Hair), alpha = 0.15, jitter = TRUE, seed = 1995) +
  labs(title = "Observed") +
  theme(legend.position = "none")

Under independence the Hair partitions must line up across all Eye columns.

ggplot(hec, aes(x = product(Hair, Eye), weight = Freq)) +
  geom_mosaic(aes(fill = Hair), expected = "independence", area = "expected",
              alpha = 0.15, jitter = TRUE, seed = 1995) +
  labs(title = "Independence: expected areas") +
  theme(legend.position = "none")

With residual shading, the pressure in each chamber is shown by its colour:

ggplot(hec, aes(x = product(Hair, Eye), weight = Freq)) +
  geom_mosaic(expected = "independence", area = "expected",
              jitter = TRUE, jitter_colour = "black", seed = 1995) +
  scale_fill_residual() +
  labs(title = "Pressure = Pearson residual")

Point options

The tiles and the points have separate transparency: alpha (default 0.8) fades only the tiles (and their outlines, unless they are residual outlines), while the points use jitter_alpha (default 1, opaque). That is why alpha = 0.15 above gives pale tiles with solid points.

base <- ggplot(hec, aes(x = product(Hair, Eye), weight = Freq))
opts <- list(
  "jitter_shape = \"first\" (default)" =
    geom_mosaic(expected = "independence", area = "expected", alpha = 0.1,
                jitter = TRUE, jitter_colour = "black", seed = 1),
  "jitter_shape = 1 (one shape)" =
    geom_mosaic(expected = "independence", area = "expected", alpha = 0.1,
                jitter = TRUE, jitter_shape = 1, jitter_colour = "black", seed = 1),
  "jitter_colour = \"fill\" (default), aes(fill = Hair)" =
    geom_mosaic(aes(fill = Hair), expected = "independence", area = "expected",
                alpha = 0.1, jitter = TRUE, seed = 1),
  "jitter_size = 2, jitter_alpha = 0.4" =
    geom_mosaic(aes(fill = Hair), expected = "independence", area = "expected",
                alpha = 0.1, jitter = TRUE, jitter_size = 2,
                jitter_alpha = 0.4, seed = 1)
)
plots <- lapply(names(opts), function(nm)
  base + opts[[nm]] + labs(title = nm) +
    theme_mosaic(base_size = 9) + theme(legend.position = "none"))
show_grid(plots, 2, 2)

seed fixes the point positions. Without it, a seed is chosen when the layer is created, so the points stay put when the plot is redrawn or resized, but differ between two calls of geom_mosaic().

Three-way tables: which model?

In product(Sex, Hair, Eye), Eye gives the columns, Hair the rows, and Sex the innermost split, so the symbols now distinguish Male and Female. The areas show what each model predicts; compare how crowded the cells are.

models <- list(
  "Mutual: ~ Hair + Eye + Sex" = "independence",
  "Joint: ~ Hair*Eye + Sex" = ~ Hair * Eye + Sex,
  "Saturated: areas = observed" = "saturated"
)
plots <- lapply(names(models), function(nm)
  ggplot(hec, aes(x = product(Sex, Hair, Eye), weight = Freq)) +
    geom_mosaic(expected = models[[nm]], area = "expected",
                jitter = TRUE, jitter_colour = "black", jitter_size = 1,
                seed = 1995) +
    scale_fill_residual(limits = c(-4, 4)) +
    labs(title = nm) +
    theme_mosaic(base_size = 8) + theme(legend.position = "none"))
show_grid(plots, 1, 3)

Joint independence fits Hair × Eye exactly, so within each Hair × Eye block only the Sex split is forced; the remaining pressure differences are small. Under the saturated model the areas are the observed ones and every chamber is in balance.

Fitting as a physical process: iterative proportional fitting

For models such as mutual or joint independence, the expected frequencies have a closed form. Others do not: the model of no three-way interaction, ~ Hair*Eye + Hair*Sex + Eye*Sex (or ~ (Hair + Eye + Sex)^2), says that each pair of variables is associated, but that the association between any two is the same at every level of the third. loglin() and MASS::loglm() fit it by iterative proportional fitting (IPF): starting from a table with all cells equal, each step rescales the fitted table so that one of the model’s margins (here Hair × Eye, Hair × Sex, Eye × Sex) matches the observed margin, and the cycle repeats until nothing changes.

In the pressure model, each IPF step releases one set of partitions and lets that margin come to balance (Friendly, 1995, eq. 3). G², the energy held in the forced partitions, falls at every step.

ipf_steps() runs IPF one margin at a time and keeps the fitted table after each step:

steps <- ipf_steps(HairEyeColor, ~ (Hair + Eye + Sex)^2)
steps
#> IPF for margins {Hair:Eye, Hair:Sex, Eye:Sex}: 5 cycles, converged
#>  step cycle   margin      G2      X2 deviation
#>     0     0    start 475.118 557.622        NA
#>     1     1 Hair:Eye  21.810  21.455  82.00000
#>     2     1 Hair:Sex  11.764  11.771  17.50000
#>     3     1  Eye:Sex   7.588   7.548  11.74540
#>     4     2 Hair:Eye   7.554   7.508   0.88706
#>     5     2 Hair:Sex   6.936   6.991   3.32986
#>     6     2  Eye:Sex   6.805   6.863   1.95025
#>     7     3 Hair:Eye   6.798   6.864   0.38461
#>     8     3 Hair:Sex   6.771   6.864   0.74165
#>     9     3  Eye:Sex   6.764   6.859   0.45123
#>    10     4 Hair:Eye   6.763   6.861   0.10019
#>    11     4 Hair:Sex   6.762   6.866   0.17316
#>    12     4  Eye:Sex   6.761   6.866   0.10740
#>    13     5 Hair:Eye   6.761   6.867   0.02430
#>    14     5 Hair:Sex   6.761   6.868   0.04094
#>    15     5  Eye:Sex   6.761   6.868   0.02552

Almost all of the work is done in the first cycle: G² falls from 475 (all cells equal) to 21.8 once Hair × Eye is balanced, to 11.8 with Hair × Sex, and to 7.6 with Eye × Sex. The remaining cycles make adjustments too small to see, converging to G² = 6.76 on 9 df.

ggplot(steps$steps, aes(step, G2)) +
  geom_line(colour = "grey50") +
  geom_point(aes(colour = margin), size = 2.5) +
  scale_y_log10() +
  labs(x = "IPF step", y = "G² (log scale)", colour = "Margin balanced") +
  theme_minimal(base_size = 11)

Selected steps

Each fitted table in steps$fits can be given directly to geom_mosaic(expected = ), with area = "expected", to draw the partitions at that step. A fixed seed keeps every observation in the same relative place in its cell, and fixed limits and breaks for the residual scale make the panels comparable.

ipf_step_plot <- function(k, base_size = 8) {
  s <- steps$steps[k + 1, ]
  title <- if (k == 0) {
    "Start: all cells equal"
  } else if (k == nrow(steps$steps) - 1) {
    sprintf("Step %d: converged fit", k)
  } else {
    sprintf("Step %d (cycle %d): balance %s", k, s$cycle, s$margin)
  }
  ggplot(hec, aes(x = product(Sex, Hair, Eye), weight = Freq)) +
    geom_mosaic(expected = steps$fits[[k + 1]], area = "expected",
                jitter = TRUE, jitter_colour = "black", jitter_size = 0.8,
                seed = 1995) +
    scale_fill_residual(limits = c(-4, 4), breaks = c(-4, -2, 0, 2, 4)) +
    labs(title = title, subtitle = sprintf("G² = %.1f", s$G2)) +
    theme_mosaic(base_size = base_size) +
    theme(legend.position = "none")
}
final <- nrow(steps$steps) - 1
show_grid(lapply(c(0, 1, 2, 3, 6, final), ipf_step_plot), 2, 3)

  • Start: every chamber has the same size, so the pressure differences are enormous: Brown hair with Brown eyes and Blond hair with Blue eyes are crowded, while Blond hair with Brown eyes and Black hair with Green eyes are nearly empty.
  • Step 1 frees the Hair and Eye partitions. The Hair × Eye blocks now have their observed sizes, and most of the pressure is gone; what remains is the Sex split within each block, still forced to be equal.
  • Steps 2 and 3 balance Hair × Sex and Eye × Sex, which moves the Sex partitions and slightly disturbs the Hair × Eye blocks again.
  • Later steps repeat the cycle, with ever smaller corrections, until the fitted table matches all three margins at once. The pressure that remains is what the model cannot remove: the three-way interaction.

The animation

Drawing the steps in sequence, and interpolating the fitted tables between them, shows the partitions moving and the observations carried along with them. The animation steps through the cycles in which G² visibly falls, then glides once to the converged fit.

Each frame is an ordinary plot. For a fraction t of the way between steps a and b:

fit <- (1 - t) * steps$fits[[a + 1]] + t * steps$fits[[b + 1]]
ggplot(hec, aes(x = product(Sex, Hair, Eye), weight = Freq)) +
  geom_mosaic(expected = fit, area = "expected", jitter = TRUE,
              jitter_colour = "black", seed = 1995) +
  scale_fill_residual(limits = c(-4, 4), breaks = c(-4, -2, 0, 2, 4))

The frames can be written with ragg::agg_png() and combined with gifski::gifski().

The two-layer form: mapped point aesthetics, legends, labels

Set the model and the area once with mosaic_settings(); every mosaic layer then uses the same cells. Point colour and shape can be mapped, with a legend, using geom_mosaic_jitter().

ggplot(hec, aes(x = product(Hair, Eye), weight = Freq)) +
  mosaic_settings(expected = "independence", area = "expected") +
  geom_mosaic(alpha = 0.15) +
  geom_mosaic_jitter(aes(colour = Hair, shape = Hair), seed = 1995) +
  scale_shape_manual(values = 15:18) +
  labs(title = "geom_mosaic() + geom_mosaic_jitter()")

Observed counts printed in the expected-area cells:

ggplot(hec, aes(x = product(Hair, Eye), weight = Freq)) +
  mosaic_settings(expected = "independence", area = "expected") +
  geom_mosaic() +
  geom_mosaic_text(display_values = "observed", format_digits = 0) +
  scale_fill_residual() +
  labs(title = "Observed counts in expected-area cells")

Comparison with vcd

vcd::mosaic(type = "expected") draws the same expected-area cells (stacking Hair from the top):

vcd::mosaic(margin.table(HairEyeColor, 1:2), expected = ~ Hair + Eye,
            type = "expected", shade = TRUE, legend = FALSE)

References

Friendly, M. (1995). Conceptual and visual models for categorical data. The American Statistician, 49, 153–160. http://doi.org/10.1080/00031305.1995.10476134
Friendly, M. (1998). Conceptual models for visualizing contingency table data. In M. Greenacre & J. Blasius (Eds.), Visualization of categorical data (pp. 17–35). San Diego, CA: Academic Press. http://doi.org/10.1016/B978-012299045-8/50003-6
Sall, J. (1991). The conceptual model for categorical responses. ASA Statistical Computing and Statistical Graphics Newsletter, 3, 33–36.