| Title: | Residual-Shaded Mosaic Plots for 'ggplot2' |
|---|---|
| Description: | 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(). |
| Authors: | Sam Butler [aut, cre] |
| Maintainer: | Sam Butler <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.1.1 |
| Built: | 2026-11-20 21:32:37 UTC |
| Source: | https://github.com/cran/mosaicresid |
The plain-data-frame engine behind geom_mosaic_resid(), with no
ggplot2 involved: converts data to long-format counts, recursively
partitions the unit square into tiles sized by joint proportion, and
attaches independence-model residuals to each tile. Returned as an
ordinary tibble, so it's directly inspectable – useful for checking the
underlying numbers, or for driving a completely custom plot.
compute_mosaic_residuals( data, x, y, weight = NULL, spacing = 0.01, dir = NULL, type = c("pearson", "deviance", "FT") )compute_mosaic_residuals( data, x, y, weight = NULL, spacing = 0.01, dir = NULL, type = c("pearson", "deviance", "FT") )
data |
A data frame – either one row per observation, or already aggregated with an existing count/weight column. |
x, y
|
Strings naming the two grouping variables. |
weight |
Optional string naming an existing count column. |
spacing |
Gap size (fraction of each split's dimension) between
sibling rectangles at every level, passed through to the internal
partitioning step. |
dir |
Optional character vector of |
type |
Residual formula: |
A tibble with one row per (x, y) cell: xmin/xmax/ymin/
ymax (tile bounds in [0,1] plot units), n (cell count), level,
the x/y category columns, row_total/col_total/expected, and
residual.
df <- data.frame( genre = sample(c("Action", "Sports", "Puzzle"), 200, replace = TRUE), platform = sample(c("PS", "Switch"), 200, replace = TRUE) ) compute_mosaic_residuals(df, "genre", "platform")df <- data.frame( genre = sample(c("Action", "Sports", "Puzzle"), 200, replace = TRUE), platform = sample(c("PS", "Switch"), 200, replace = TRUE) ) compute_mosaic_residuals(df, "genre", "platform")
Registers a method so ggplot(some_table) works directly on a base R
table (e.g. Titanic, HairEyeColor, UCBAdmissions) – matching how
base R's own mosaicplot() accepts a table as x. Without this method,
ggplot() rejects a table object outright, since ggplot2 only
fortifies objects it has a registered method for.
## S3 method for class 'table' fortify(model, data, ...)## S3 method for class 'table' fortify(model, data, ...)
model |
A |
data |
Unused; present for compatibility with the |
... |
Unused. |
This is intentionally just as.data.frame(): a table's cell values
already are the counts, so converting always produces one column per
table dimension plus a literal Freq count column. See
geom_mosaic_resid() for how that Freq column is then used
automatically as an implicit weight.
A data frame with one row per table cell.
The main entry point for this package. A ggplot2-native equivalent of
base R's mosaicplot(shade = TRUE): give it two categorical variables
the normal ggplot2 way, aes(x =, y =), and it draws a true mosaic plot
(tiles sized by joint proportion, not a grid approximation), shaded by
independence-model residuals, with in-tile category labels – no manual
stat work required.
geom_mosaic_resid( mapping = NULL, data = NULL, stat = "mosaic_residual", position = "identity", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, spacing = 0.01, label = TRUE, min_label_width = 0.02, min_label_height = 0.03, label.size = 3, label.color = "black", default_scale = TRUE, scale_low = "firebrick", scale_mid = "white", scale_high = "steelblue", scale_midpoint = 0, dir = NULL, type = c("pearson", "deviance", "FT"), ... )geom_mosaic_resid( mapping = NULL, data = NULL, stat = "mosaic_residual", position = "identity", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, spacing = 0.01, label = TRUE, min_label_width = 0.02, min_label_height = 0.03, label.size = 3, label.color = "black", default_scale = TRUE, scale_low = "firebrick", scale_mid = "white", scale_high = "steelblue", scale_midpoint = 0, dir = NULL, type = c("pearson", "deviance", "FT"), ... )
mapping |
Set of aesthetic mappings created by |
data |
The data to be displayed in this layer. There are three options: If A A |
stat |
The statistical transformation to use on the data for this layer.
When using a
|
position |
A position adjustment to use on the data for this layer. This
can be used in various ways, including to prevent overplotting and
improving the display. The
|
na.rm |
If |
show.legend |
logical. Should this layer be included in the legends?
|
inherit.aes |
If |
spacing |
Gap between sibling tiles, as a fraction of their parent's dimension. |
label |
Set to |
min_label_width, min_label_height
|
Minimum cell width/height (0-1 fractional units) required for a label to be drawn; smaller cells are colored but left unlabeled rather than overflowing. |
label.size, label.color
|
Passed through to the label's
|
default_scale |
Set |
scale_low, scale_mid, scale_high, scale_midpoint
|
Passed through to
the default scale ( |
dir |
Optional character vector of |
type |
Residual formula: |
... |
Other arguments passed on to
|
Returns a list of ggplot2 layers/scales – the rectangles (GeomRect),
in-tile category labels (GeomText), and a default diverging fill scale
– so a single call gives you all three. ggplot2 natively supports
+-ing a list of layers/scales onto a plot, so this composes just like a
normal single-layer geom would.
A list of ggplot2 layers (and, by default, a scale), suitable
for adding to a ggplot() call with +.
library(ggplot2) df <- data.frame( genre = sample(c("Action", "Sports", "Puzzle"), 200, replace = TRUE), platform = sample(c("PS", "Switch"), 200, replace = TRUE) ) # colors, spacing, and labels all come for free -- no manual # scale_fill_gradient2() call needed, it's the default ggplot(df) + geom_mosaic_resid(aes(x = genre, y = platform)) + theme_minimal() # the default scale is fully overridable like any ggplot2 layer ggplot(df) + geom_mosaic_resid(aes(x = genre, y = platform)) + scale_fill_gradient2(low = "purple", mid = "white", high = "darkgreen") + theme_minimal()library(ggplot2) df <- data.frame( genre = sample(c("Action", "Sports", "Puzzle"), 200, replace = TRUE), platform = sample(c("PS", "Switch"), 200, replace = TRUE) ) # colors, spacing, and labels all come for free -- no manual # scale_fill_gradient2() call needed, it's the default ggplot(df) + geom_mosaic_resid(aes(x = genre, y = platform)) + theme_minimal() # the default scale is fully overridable like any ggplot2 layer ggplot(df) + geom_mosaic_resid(aes(x = genre, y = platform)) + scale_fill_gradient2(low = "purple", mid = "white", high = "darkgreen") + theme_minimal()
The classic S3 ggplot_add() method that handles +-ing a
mosaicresid_layers list onto a plot on ggplot2 versions before the
4.0 S7 rewrite. See add_mosaicresid_layers() for what this actually
does; on ggplot2 >= 4.0 the equivalent work happens via the S7 method
registered in zzz.R instead, since this S3 method is never reached
there.
## S3 method for class 'mosaicresid_layers' ggplot_add(object, plot, object_name, ...)## S3 method for class 'mosaicresid_layers' ggplot_add(object, plot, object_name, ...)
object |
A |
plot |
The |
object_name |
The name of |
... |
Unused; present for compatibility with the |
The updated ggplot object.
A continuous red-white-blue gradient (red = negative residual / under-represented, blue = positive / over-represented), rather than base R's discrete HSV-stepped bins. Chosen as the default because it reads better alongside in-tile labels – there's no hard color-bin boundary cutting across a cell's text the way base R's stepped bins can. It's still an ordinary ggplot2 scale object, so it composes and overrides the usual way.
scale_fill_mosaic_residual( low = "firebrick", mid = "white", high = "steelblue", midpoint = 0, name = "Residual", ... )scale_fill_mosaic_residual( low = "firebrick", mid = "white", high = "steelblue", midpoint = 0, name = "Residual", ... )
low, mid, high
|
Colors for the most negative, zero, and most positive residual. |
midpoint |
Residual value treated as the color midpoint ( |
name |
Legend title. |
... |
Passed on to |
A ggplot2 ScaleContinuous object.
library(ggplot2) df <- data.frame( genre = sample(c("Action", "Sports", "Puzzle"), 200, replace = TRUE), platform = sample(c("PS", "Switch"), 200, replace = TRUE) ) ggplot(df) + geom_mosaic_resid(aes(x = genre, y = platform), default_scale = FALSE) + scale_fill_mosaic_residual()library(ggplot2) df <- data.frame( genre = sample(c("Action", "Sports", "Puzzle"), 200, replace = TRUE), platform = sample(c("PS", "Switch"), 200, replace = TRUE) ) ggplot(df) + geom_mosaic_resid(aes(x = genre, y = platform), default_scale = FALSE) + scale_fill_mosaic_residual()
The stat underlying geom_mosaic_resid()'s in-tile category labels.
Use this directly if you want the labels without the default rectangles
and fill scale.
stat_mosaic_label( mapping = NULL, data = NULL, geom = "text", position = "identity", na.rm = FALSE, spacing = 0.01, min_label_width = 0.02, min_label_height = 0.03, dir = NULL, show.legend = FALSE, inherit.aes = TRUE, ... )stat_mosaic_label( mapping = NULL, data = NULL, geom = "text", position = "identity", na.rm = FALSE, spacing = 0.01, min_label_width = 0.02, min_label_height = 0.03, dir = NULL, show.legend = FALSE, inherit.aes = TRUE, ... )
mapping |
Set of aesthetic mappings created by |
data |
The data to be displayed in this layer. There are three options: If A A |
geom |
The geometric object to use to display the data for this layer.
When using a
|
position |
A position adjustment to use on the data for this layer. This
can be used in various ways, including to prevent overplotting and
improving the display. The
|
na.rm |
If |
spacing |
Gap between sibling tiles, as a fraction of their parent's
dimension – must match whatever |
min_label_width, min_label_height
|
Minimum cell width/height (in 0-1 fractional plot units) required for a label to be drawn at all. Tune these per-plot: smaller plots or longer category names typically need larger thresholds to avoid overflow. |
dir |
Optional character vector of |
show.legend |
logical. Should this layer be included in the legends?
|
inherit.aes |
If |
... |
Other arguments passed on to
|
A ggplot2 layer object (class LayerInstance) that can be
added to a plot with +. When the plot is built, the layer writes each
tile's x and y category names at the center of that tile, skipping
tiles too small to hold the text.
library(ggplot2) df <- data.frame( genre = sample(c("Action", "Sports", "Puzzle"), 200, replace = TRUE), platform = sample(c("PS", "Switch"), 200, replace = TRUE) ) ggplot(df) + stat_mosaic_residual(aes(x = genre, y = platform)) + stat_mosaic_label(aes(x = genre, y = platform))library(ggplot2) df <- data.frame( genre = sample(c("Action", "Sports", "Puzzle"), 200, replace = TRUE), platform = sample(c("PS", "Switch"), 200, replace = TRUE) ) ggplot(df) + stat_mosaic_residual(aes(x = genre, y = platform)) + stat_mosaic_label(aes(x = genre, y = platform))
The stat underlying geom_mosaic_resid()'s rectangles. Use this
directly if you want to pair the mosaic-residual computation with a geom
other than GeomRect.
stat_mosaic_residual( mapping = NULL, data = NULL, geom = "rect", position = "identity", na.rm = FALSE, spacing = 0.01, dir = NULL, type = c("pearson", "deviance", "FT"), show.legend = NA, inherit.aes = TRUE, ... )stat_mosaic_residual( mapping = NULL, data = NULL, geom = "rect", position = "identity", na.rm = FALSE, spacing = 0.01, dir = NULL, type = c("pearson", "deviance", "FT"), show.legend = NA, inherit.aes = TRUE, ... )
mapping |
Set of aesthetic mappings created by |
data |
The data to be displayed in this layer. There are three options: If A A |
geom |
The geometric object to use to display the data for this layer.
When using a
|
position |
A position adjustment to use on the data for this layer. This
can be used in various ways, including to prevent overplotting and
improving the display. The
|
na.rm |
If |
spacing |
Gap between sibling tiles, as a fraction of their parent's dimension. |
dir |
Optional character vector of |
type |
Residual formula: |
show.legend |
logical. Should this layer be included in the legends?
|
inherit.aes |
If |
... |
Other arguments passed on to
|
A ggplot2 layer object (class LayerInstance) that can be
added to a plot with +. When the plot is built, the layer draws one
tile per combination of the x and y categories, sized by that
combination's share of the total count and filled by its residual
against a two-way independence model (positive = more observations
than independence predicts, negative = fewer).
library(ggplot2) df <- data.frame( genre = sample(c("Action", "Sports", "Puzzle"), 200, replace = TRUE), platform = sample(c("PS", "Switch"), 200, replace = TRUE) ) ggplot(df) + stat_mosaic_residual(aes(x = genre, y = platform))library(ggplot2) df <- data.frame( genre = sample(c("Action", "Sports", "Puzzle"), 200, replace = TRUE), platform = sample(c("PS", "Switch"), 200, replace = TRUE) ) ggplot(df) + stat_mosaic_residual(aes(x = genre, y = platform))
Computes label text + centroid position for each mosaic cell, so category names can be drawn directly inside their rectangles. This sidesteps a real constraint of mosaic plots: the inner variable's split positions differ from column to column (they're conditional on the outer variable), so there's no single shared axis tick that's correct for the whole plot. In-tile labels are the structurally correct fix, not a workaround.
Cells smaller than min_label_width/min_label_height (in the same 0-1
fractional units as xmin/xmax/ymin/ymax) are dropped from the
label set entirely – they're still colored by the rect layer, just with
no text crammed into a sliver. These are exposed as tunable parameters
because the "right" threshold depends on plot size, font size, and label
text length, not on the data alone.
A ggproto object of class StatMosaicLabel (inheriting from
ggplot2::Stat). It is not called directly; it is the stat used by
stat_mosaic_label() and by the label layer of geom_mosaic_resid().
During plot building it returns one row per labeled tile, with the
tile's center (x, y) and its label text (the x and y
categories on two lines). Tiles smaller than min_label_width or
min_label_height are left out.
Takes discrete catx/caty aesthetics (and optional weight), computes
mosaic rectangles + independence residuals, and hands
xmin/xmax/ymin/ymax + residual off to a geom (GeomRect by
default).
A ggproto object of class StatMosaicResidual (inheriting
from ggplot2::Stat). It is not called directly; it is the stat
used by stat_mosaic_residual() and geom_mosaic_resid(). During
plot building it returns one row per combination of the x and y
categories, with tile bounds xmin, xmax, ymin, ymax (in 0-1
plot units), the cell count n, the expected count under
independence, and the residual used for the fill color.
Accepts either one-row-per-observation data or data already aggregated
with an existing count column (via weight), and returns a single tidy
long-format count table either way – the same code path is used
downstream regardless of which kind of input was supplied.
to_long_counts(data, x, y, weight = NULL)to_long_counts(data, x, y, weight = NULL)
data |
A data frame – either one row per observation, or already aggregated with an existing count/weight column. |
x, y
|
Strings naming the two grouping variables. |
weight |
Optional string naming an existing count column. Leave
|
NA handling matches base R's table()/mosaicplot() default
(useNA = "no"): rows with NA in either grouping variable are silently
excluded, not counted as their own category. Unused factor levels are
dropped so phantom zero-total categories never enter the partitioning
step.
A tibble with columns x, y, and n (named after the values of
the x/y arguments, plus a literal n count column).
df <- data.frame( genre = sample(c("Action", "Sports", "Puzzle"), 200, replace = TRUE), platform = sample(c("PS", "Switch"), 200, replace = TRUE) ) to_long_counts(df, "genre", "platform")df <- data.frame( genre = sample(c("Action", "Sports", "Puzzle"), 200, replace = TRUE), platform = sample(c("PS", "Switch"), 200, replace = TRUE) ) to_long_counts(df, "genre", "platform")