Getting Started with mosaicresid

library(mosaicresid)
library(ggplot2)

Why this package exists

Base R’s mosaicplot(shade = TRUE) is a genuinely useful plot: tile area encodes joint proportion, and tile color encodes how far each cell departs from what independence would predict (a Pearson residual). But it’s drawn with base graphics, so it can’t be faceted, themed, or composed with other ggplot2 layers, and it returns nothing you can inspect – the numbers only ever reach a device.

mosaicresid reproduces the same statistics and the same true mosaic geometry (recursive partitioning, not a grid-of-equal-cells approximation), but as an ordinary ggplot2 layer, mapped the way every other ggplot2 geom is mapped:

ggplot(infert) +
  geom_mosaic_resid(
    aes(x = factor(pmin(spontaneous, 2), labels = c("Zero", "One", "2 or more")),
        y = factor(case, labels = c("Control", "Case")))) +
  theme_minimal() +
  labs(title = "Prior Spontaneous Abortions vs Infertility Case Status",
       x = "Spontaneous abortions", y = NULL)

That single call did everything base R’s mosaicplot(shade = TRUE) does:

Working with raw or pre-aggregated data

geom_mosaic_resid() accepts the shapes of input base R’s mosaicplot() does, plus ordinary data frames. The infert example above was raw data, one row per subject. The example below is an ordinary data frame:

ggplot(Titanic) +
  geom_mosaic_resid(aes(x = Class, y = Survived)) +
  labs(title = "Titanic Survival Rate by Class", x = "Class") +
  theme_minimal()

A table’s cell values already are the counts. When a table is passed in, it becomes a data frame with a count column named Freq (the name as.data.frame() always gives it), and that column is used as the weight automatically.

If your counts live in a column with any other name, map it to the weight aesthetic yourself, inside aes() and unquoted, the same way weight works for stat_count() or stat_bin():

titanic_counts <- aggregate(Freq ~ Class + Survived, as.data.frame(Titanic), sum)
names(titanic_counts)[names(titanic_counts) == "Freq"] <- "passengers"

ggplot(titanic_counts) +
  geom_mosaic_resid(aes(x = Class, y = Survived, weight = passengers)) +
  labs(title = "Titanic Survival Rate by Class (pre-aggregated counts)", x = "Class") +
  theme_minimal()

An explicit weight mapping always takes priority over the automatic Freq detection.

Overriding the color scale

The examples below use mtcars. Its columns are stored as numbers, so we first build a small data frame with readable category labels and reuse it for the rest of this vignette:

cars <- data.frame(
  cylinders    = factor(mtcars$cyl,  labels = c("4 cylinders", "6 cylinders", "8 cylinders")),
  transmission = factor(mtcars$am,   labels = c("Automatic", "Manual")),
  gears        = factor(mtcars$gear, labels = c("3 gears", "4 gears", "5 gears"))
)

The default scale is an ordinary ggplot2 scale object, so you override it the usual way, and labels keep working when you do:

ggplot(cars) +
  geom_mosaic_resid(aes(x = cylinders, y = transmission)) +
  scale_fill_gradient2(low = "purple", mid = "white", high = "darkgreen") +
  theme_minimal() +
  labs(title = "Cylinders vs Transmission", x = NULL, y = NULL)
#> Scale for fill is already present.
#> Adding another scale for fill, which will replace the existing scale.

Spacing, labels, and small cells

ggplot(cars) +
  geom_mosaic_resid(
    aes(x = cylinders, y = gears),
    spacing = 0.02,
    min_label_width = 0.04,
    min_label_height = 0.06,
    label.size = 2.5
  ) +
  theme_minimal() +
  labs(title = "Cylinders vs Gears", x = NULL, y = NULL)

Cells smaller than min_label_width/min_label_height (in 0-1 fractional plot units) are still colored, just left unlabeled, rather than overflowing text across tile boundaries.

This plot also has an empty cell: no car in mtcars has 8 cylinders and 4 gears. As in base R, that combination is kept as a zero-count tile with zero height, not dropped, and its residual is still computed. A missing combination is often exactly the departure from independence you want to see.

Matching base R’s dir and type options

Base R’s mosaicplot() lets you force the split direction per variable (dir) and choose among three residual formulas (type). Both are supported here with the same meaning:

ggplot(cars) +
  geom_mosaic_resid(
    aes(x = cylinders, y = transmission),
    dir = c("h", "v"),   # swap which variable splits vertically first
    type = "deviance"    # pearson (default), deviance, or FT (Freeman-Tukey)
  ) +
  theme_minimal() +
  labs(title = "Cylinders vs Transmission (deviance residuals, swapped splits)",
       x = NULL, y = NULL)

Inspecting the numbers directly

The statistics come from a plain function, not hidden inside a device call, so you can get the tile geometry and residuals as an ordinary data frame. That’s useful for checking the math or for driving a completely custom plot:

compute_mosaic_residuals(cars, "cylinders", "transmission")
#> # A tibble: 6 × 12
#>    xmin  xmax  ymin  ymax     n level cylinders transmission row_total col_total
#>   <dbl> <dbl> <dbl> <dbl> <int> <dbl> <fct>     <fct>            <int>     <int>
#> 1 0     0.337 0     0.27      3     2 4 cylind… Automatic           11        19
#> 2 0     0.337 0.28  1         8     2 4 cylind… Manual              11        13
#> 3 0.347 0.561 0     0.566     4     2 6 cylind… Automatic            7        19
#> 4 0.347 0.561 0.576 1         3     2 6 cylind… Manual               7        13
#> 5 0.571 1     0     0.849    12     2 8 cylind… Automatic           14        19
#> 6 0.571 1     0.859 1         2     2 8 cylind… Manual              14        13
#> # ℹ 2 more variables: expected <dbl>, residual <dbl>

What this package deliberately does not do

compute_mosaic_residuals() supports only two grouping variables. Past two variables, “expected count” stops having one unambiguous definition: complete independence, joint independence, conditional independence, and all-two-way-associations are different loglinear models, and you have to pick one. Rather than silently compute a plausible-looking but wrong number, the package fails loudly when given more than two variables and points you to stats::loglin() or glm(family = poisson) for fitting a model you’ve chosen explicitly. See vignette("comparison") for how this scope decision compares to the alternatives.