--- title: "Getting Started with mosaicresid" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Getting Started with mosaicresid} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>", fig.width = 7, fig.height = 5 ) ``` ```{r setup} 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: ```{r} 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: - **Sized** each tile by its joint proportion (true mosaic geometry: width from the first variable's marginal split, height from the second variable's split *conditional* on the first). - **Computed** a two-way independence model and the Pearson residual of each cell against it. - **Colored** each tile by that residual, via a diverging red-white-blue scale. - **Labeled** each tile in place, since the usual axis-tick labeling doesn't work for a mosaic plot's inner variable (its split positions differ from column to column -- there's no one shared axis position that's correct for the whole plot). ## 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: ```{r} 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()`: ```{r} 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: ```{r} 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: ```{r} 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) ``` ## Spacing, labels, and small cells ```{r} 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: ```{r} 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: ```{r} compute_mosaic_residuals(cars, "cylinders", "transmission") ``` ## 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.