A 'ggplot2'-native alternative to the shaded mosaic plots drawn by mosaicplot() in base 'R'. geom_mosaic_resid() maps two categorical variables with ordinary 'ggplot2' aesthetics, recursively partitions the unit square into tiles sized by their joint proportions, computes Pearson, deviance, or Freeman-Tukey residuals against a two-way independence model, and maps the residuals to fill color. It works on raw data, already aggregated counts, or contingency tables, and the tile geometry and residuals are also returned as a data frame by compute_mosaic_residuals().
A ggplot2-native alternative to base R's mosaicplot(shade = TRUE).
library(mosaicresid)
library(ggplot2)
ggplot(Titanic) +
geom_mosaic_resid(aes(x = Class, y = Survived)) +
theme_minimal()
geom_mosaic_resid() takes two categorical variables mapped the usual
ggplot2 way, aes(x =, y =), and automatically:
Works on raw, one-row-per-observation data or already-aggregated
contingency-table data through the same code path, and the underlying
tile geometry and residuals are available directly as a tidy data frame
via compute_mosaic_residuals().
# development version from GitHub
# install.packages("remotes")
remotes::install_github("sbutler22/geom_mosaic")
vignette("getting-started", package = "mosaicresid")vignette("comparison", package = "mosaicresid") -- an honest comparison
against base R's mosaicplot() and the ggmosaic2 package, including
what this package deliberately does and does not implement.MIT
This package was developed with substantial help from Claude (Anthropic),
used as a coding assistant. Claude drafted much of the R code, roxygen
documentation, tests, and vignette text, and helped debug issues such as
compatibility with ggplot2 4.0. I directed the design (including the
aes(x =, y =) interface, the two-variable scope, and the default color
scale), reviewed and tested the code, chose the example datasets, and
edited the documentation. The residual calculations are checked against
base R's own mosaicplot() formulas in the package's test suite.