Skip to contents

The statistic builds one complete contingency table per panel. Map an optional count to weight. All fill groups share one denominator and one model. Mapped fill, colour, alpha, linewidth and linetype must be constant within each cell. For a complete set of category colours including unused levels use, for example, after_stat(.mosaic_keys$Sex). The layer returns observed, expected, residual and proportion, the plotted area shares area_proportion and conditional_area_proportion, rectangle bounds, label centres, original dimension columns in the data frame .mosaic_keys, and the panel fit summary in the first cell's .mosaic_diagnostics. Use the selected residual in after_stat(residual). Use ggmosaic() for measured hierarchy and leaf labels, translated guides and zero markers. Position scales must use continuous identity transforms. Tile areas represent the selected observed or expected frequencies in linear Cartesian coordinates with zero gaps.

Usage

geom_mosaic(
  mapping = NULL,
  data = NULL,
  stat = "mosaic",
  position = "identity",
  ...,
  vars = NULL,
  model = "independence",
  expected = NULL,
  structural = NULL,
  given = NULL,
  residual = "pearson",
  weight_type = "frequency",
  direction = NULL,
  gap = 0,
  sort = "level",
  max_cells = 100000L,
  na.rm = FALSE,
  show.legend = NA,
  inherit.aes = TRUE,
  type = "observed",
  zero_split = FALSE,
  layout_size = NULL,
  residuals = NULL
)

stat_mosaic(
  mapping = NULL,
  data = NULL,
  geom = "mosaic",
  position = "identity",
  ...,
  vars = NULL,
  model = "independence",
  expected = NULL,
  structural = NULL,
  given = NULL,
  residual = "pearson",
  weight_type = "frequency",
  direction = NULL,
  gap = 0,
  sort = "level",
  max_cells = 100000L,
  na.rm = FALSE,
  show.legend = NA,
  inherit.aes = TRUE,
  type = "observed",
  zero_split = FALSE,
  layout_size = NULL,
  residuals = NULL
)

Arguments

mapping

Mappings from ggplot2::aes(). Use computed values with ggplot2::after_stat(). A mapped group does not split a panel's table.

data

Layer data. The default inherits the plot's data.

stat, geom

Statistic or geom for this layer. With stat = "identity" supply finished xmin, xmax, ymin and ymax aesthetics and omit vars.

position

Identity position adjustment.

...

Other layer parameters or fixed aesthetics.

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.

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.

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.

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.

na.rm

Passed to the geom. Invalid frequencies always produce an error.

show.legend, inherit.aes

Standard ggplot2 layer controls.

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.

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.

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.

Value

A ggplot2 layer.

Examples

d <- as.data.frame(Titanic)
ggplot2::ggplot(d) +
  geom_mosaic(ggplot2::aes(weight = Freq, fill = ggplot2::after_stat(residual)),
              vars = c(Class, Sex, Age)) +
  ggplot2::facet_wrap(~ Survived) + ggplot2::coord_fixed()

ggplot2::ggplot(d, ggplot2::aes(weight = Freq)) +
  stat_mosaic(ggplot2::aes(x = ggplot2::after_stat(label_x),
                           y = ggplot2::after_stat(label_y),
                           label = ggplot2::after_stat(observed)),
              vars = c(Class, Sex), geom = "text") +
  ggplot2::coord_fixed()