Skip to contents

The Mosaic statistic calculates a complete, independent layout inside each ggplot2 panel from its original rows. Category IDs determine grouping, ordering and colour. Translations affect only displayed text. Each panel must have a positive total. Residual shades describe deviations from the selected model; the cut points are not multiplicity-adjusted tests.

Usage

ggmosaic(
  x,
  ...,
  data = NULL,
  vars = NULL,
  weight = NULL,
  facet = NULL,
  model = "independence",
  expected = NULL,
  structural = NULL,
  weight_type = "frequency",
  direction = NULL,
  gap = 0,
  sort = "level",
  max_cells = 100000L,
  shade = "none",
  category = NULL,
  cuts = c(2, 4),
  label = "level",
  hierarchy = TRUE,
  label_format = "plain",
  label_size = 9,
  family = "sans",
  padding = grid::unit(1, "mm"),
  angle = 0,
  mark_zero = FALSE,
  border = "white",
  linewidth = 0.25,
  linetype = 1,
  lang = NULL,
  dictionary = NULL,
  given = NULL,
  residual = "pearson",
  colours = NULL,
  hierarchy_label = "{level}",
  label_hjust = 0.5,
  label_vjust = 0.5,
  type = c("observed", "expected"),
  condvars = NULL,
  highlighting = NULL,
  highlighting_direction = NULL,
  highlighting_fill = NULL,
  split_vertical = NULL,
  zero_split = FALSE,
  zero_size = 1.7,
  zero_shade = FALSE,
  labeling = NULL,
  label_sides = NULL,
  label_rotation = NULL,
  view = c("mosaic", "doubledecker", "spine", "conditional"),
  subset = NULL,
  na.action = NULL,
  panel = NULL,
  label_repeat = TRUE,
  label_abbrev = NULL,
  breaks = NULL,
  fit_scope = c("panel", "table"),
  layout_size = NULL,
  residuals = NULL,
  residual_title = NULL,
  zero_gp = grid::gpar(),
  zero_pch = 4L,
  label_style = "plain",
  global_test = NULL,
  global_alpha = 0.05
)

Arguments

x

A data frame, formula, numeric array, table, xtabs, ftable, vcd structable, or MASS loglm fit saved with fitted = TRUE and keep.frequencies = TRUE. In a formula, response ~ predictors | strata splits by strata first, then predictors, then response. Either the response or strata can be omitted. A dot selects remaining dimensions. Formulas on tables may collapse omitted dimensions. On data frames, explicitly selected numeric codes are treated as levels.

...

Must be empty. Supply further options by exact name.

data

Data frame supplying a formula, or the dataset when x is omitted.

vars

Two or more categorical columns, e.g. c(region, sex). Quoted names and all_of(name_vector) are supported. Character levels follow first appearance. Set factor levels for a custom order.

weight

Optional single column of counts or descriptive weights.

facet

Optional data-frame column(s) to facet using facet_wrap(). Ordinary + facet_wrap() or + facet_grid() on the original columns also triggers independent per-panel model fitting and geometry.

model

"independence" (mutual independence), "conditional", "none", "custom", a one-sided hierarchical log-linear formula made from dimension names, or a fitted Poisson log-link GLM. A GLM must store a model frame with one matching row per possible cell, all original dimension keys and the same counts, with unit prior weights. A fitted MASS loglm object must retain both its fitted and frequency arrays. Its generating margins are checked to relative tolerance 1e-6 using max(1, observed) as denominator. Its reported df is stored separately.

expected, structural

Aligned arrays as in mosaic_layout(). May also be functions of the panel's count array returning the corresponding array.

weight_type

Frequency counts must be finite nonnegative integers. Use "survey" with model = "none" for descriptive weighted areas.

direction

One value or one per split. "x", "v", and "right" place levels from left to right. "y" and "top" place them bottom to top. "left" reverses the horizontal order. "h" and "bottom" place levels top to bottom like a printed table. The default alternates x and y.

gap

Fraction of each parent span reserved for space between positive siblings, in [0, 1). Supply one number or one per depth. The "hierarchical" preset reserves 0.055 times 0.60 to the power of depth minus one. "conditional" separates the conditioning dimensions in given more strongly and uses 0.016 for other dimensions. Absolute grid lengths specify the distance between adjacent positive siblings at the target layout_size. A function receives one named list with depth, variable, axis, parent, level order and mass. It may return one total fraction, individual gap fractions, or absolute gap units.

sort

Preserve level order ("level") or order each parent's children by decreasing mass ("decreasing"). Can vary by depth. Ties preserve level order.

max_cells

Limit on the dense cross-product. The combined number of hierarchy nodes is also limited to eight times this value.

shade

One of "none", "pearson" (continuous Pearson), "residual" (continuous selected residual), "bands" (signed levels of the selected residual) or "category". TRUE or "hcl" uses stepped diverging colours. "friendly" adds classic signed outlines. A mosaic_max_test() result uses calibrated shading for its original fixed-margin Pearson model.

category

Original dimension name for category shading.

cuts

Increasing positive cut points on absolute selected residuals.

label

Leaf label. Use NULL to omit, a function of the complete panel cell table returning one value per row, a field name, or a string template such as "\{level\}\n\{observed\}". Fields include level, variable, observed, expected, residual, proportion, conditional_proportion, percent and conditional_percent.

hierarchy

TRUE for all internal depths, FALSE for none, or the integer depths to label. Each internal group gets a separate candidate heading. Labels that cannot fit inside their groups are omitted.

label_format

Leaf label grammar: "plain", "markdown" or "formula". For a formula supply a literal plotmath string or a callback generating valid strings, independently of display language. With markdown and a function the caller supplies ready-to-render markup. Text inserted into a markup template is escaped.

label_size

Text size in points.

family

Installed font family used for cell and hierarchy labels.

padding

Space inside a tile between its edge and text, as a grid unit.

angle

Leaf label rotation in degrees.

mark_zero

Draw a cross for sampling zeros. Structural zeros are excluded.

border, linewidth, linetype

Tile outline colour, width and type.

lang

Optional BCP 47 display language, independent of split direction.

dictionary

Optional local translation table accepted by forma_labels(). The dimension name is the lookup variable for category levels.

given

Character vector of conditioning dimensions for model = "conditional". At least two dimensions must remain. Each combination of the conditioning levels defines a separate stratum.

residual

Residual returned in the residual column. Choices are "pearson", "standardized" (Poisson Pearson divided by the square root of one minus leverage), signed Poisson "deviance", and "FT" (Freeman-Tukey, square root of observed plus square root of observed plus one, minus the square root of four times expected plus one). An expected array alone cannot supply leverage. Unit leverage or zero expectation gives an undefined standardized residual.

colours

Optional residual colours from negative to positive. For a continuous scale supply three colours, and for bands one per level.

hierarchy_label

Internal heading template. Fields include level, variable, observed, percent and conditional_percent. A function receives the eligible nodes and returns one string per row.

label_hjust, label_vjust

Placement of the measured leaf label within free tile space, from 0 (left or bottom) to 1 (right or top).

type

Use "observed" or "expected" frequencies for the area. Expected area requires a fitted model or supplied expected counts. The observed frequencies, observed shares and fitted residuals are available in both displays.

condvars

Conditioning dimension names or indices. Their empirical masses determine the size of each stratum. With two or more remaining dimensions the default model fits mutual independence within strata.

highlighting

A single response dimension name or index. It is split last and highlighted by category by default. A two-sided formula does this too.

highlighting_direction

Direction in which the response levels advance: "top", "bottom", "left" or "right".

highlighting_fill

Optional category colours in factor order, or named by original ID.

split_vertical

Logical scalar or vector by depth. TRUE advances from left to right and FALSE from top to bottom. Use either this or direction.

zero_split

If TRUE, subdivide the remaining span of a zero-mass parent equally among its levels. Their areas remain zero. The default places their anchors together at the starting edge of the parent split.

zero_size

Size in millimetres of the sampling-zero marker. Supplying a positive size enables marks by default. A size of zero hides them.

zero_shade

Use each cell's fill colour for its sampling-zero marker.

labeling

Place labels along the "border", in "cells", in "both", or use "none". Default is border. Explicit leaf or hierarchy settings retain the cell-label behaviour of earlier versions. Alternatively, supply a function of layout and margins. On each draw it receives the panel's complete layout and a data frame of candidates with original node IDs, translated labels, anchors, bounds, panel width and height, and text metrics in millimetres. Return a data frame with node and any subset of the original candidates. You may replace label, title, angle, automatic and style. Title, angle, automatic rotation and style must be consistent within a depth. Empty output hides the border. Device-specific callbacks affect static drawing. They may run again on resize or export.

label_sides, label_rotation

Optional border sides or rotation angles, scalar, by depth, or named by dimension. Use side "none" to omit a dimension.

view

"mosaic" uses the chosen split directions. "doubledecker" uses predictor widths and response heights. The last dimension supplies the response unless specified. "spine" uses one predictor, binning numeric data into a spinogram. Its x tick positions are cumulative bin shares. "conditional" draws an equal-sized panel per conditioning stratum with its own fitted model and local area denominator.

subset

Optional row selection, evaluated in the input data before aggregation. Use a logical vector or positive row indices.

na.action

Optional missing-data function on the selected columns of raw data, such as stats::na.omit(). The default diagnoses missing values.

panel

Optional function of a computed, single-row cell data frame. Return a grid grob (or NULL) to draw within its tile's clipped viewport. Keys are available as .mosaic_keys. For interactive marks use a ggplot2 layer with stat_mosaic() instead of a device-specific grob.

label_repeat, label_abbrev

Border label controls by dimension. Set repeat to FALSE to label the widest occurrence of each original level. Set a maximum grapheme count to shorten translated text with an ellipsis.

breaks

Numeric bin boundaries, bin count or histogram rule for a spinogram. Default is Sturges. Intervals close on the right and include the lowest endpoint. Set cut points explicitly for comparable editions.

fit_scope

For a conditional display, "panel" fits each stratum separately. "table" fits the entire keyed contingency table once and projects its expectations and residuals into the corresponding panels. Geometry is normalized within each panel in both displays.

layout_size

Optional target tile field width and height in millimetres. Absolute grid unit gaps use this field, defaulting to 100 by 100 mm. A high-level plot fixes its panel to this size plus border label space. Supply enough device space for all panels, titles and legends.

residuals

Optional numeric residual array with named dimensions matching the original counts, or a function of the observed and expected arrays returning such an array. Use NA for undefined values. This replaces the displayed residual and preserves built-in model diagnostics. For independently fitted panels supply a function. With a table-wide fit the function runs once on the complete table.

residual_title

Optional plain-text display name for supplied residuals. A user dictionary can translate this text in the stat context.

zero_gp

Grid graphical parameters for zero marks. Use scalar col, fill, lwd and alpha. Shading overrides the outline and fill colours.

zero_pch

Grid point shape (0 to 25). Filled symbols 21 to 25 use separate outline and interior colours. The default is a cross.

label_style

Border level style by dimension, following the same naming rules as label_sides. Choose "plain", "boxed", "left", or "boxed_left". Left alignment starts at the lower-coordinate edge of each conditional interval and adjusts for physical collisions.

global_test

Optional pure function of the full keyed frequency array, returning an htest with a p.value and method. With HCL or Friendly shading a global p above global_alpha reduces fill chroma. Cell bands stay descriptive. The chosen test is called once and frozen with its table.

global_alpha

Tail probability used only to switch the global palette.

Value

A standard ggplot. ggplot2::layer_data(plot, 1) gives the computed cells with panel IDs, observations, model diagnostics, original IDs in .mosaic_keys, and bounds. mosaic_layout() returns the hierarchy directly for numeric array input. Use linear Cartesian coordinates.

Examples

ggmosaic(HairEyeColor, shade = "bands", hierarchy = 1)

d <- as.data.frame(Titanic)
ggmosaic(~ Class + Age, data = d, weight = Freq, facet = Survived)