Written and maintained by CASRAI Editorial Board
Published
On this page
To make a mosaic plot in R, create a contingency table and pass it to graphics::mosaicplot(). Tiles represent combinations of categorical levels, with areas proportional to their counts. Start by checking whether your input contains individual observations or an already summarized frequency column: confusing those two inputs can produce a plausible picture of the wrong counts.
What R mosaic plots are used for in research
Mosaic plots display relationships among categorical variables. A two-variable display combines the size of each group with the distribution of categories inside that group. Unlike an equal-width percentage bar chart, it retains information about how common the groups are. Jeppson and Hofmann explain this connection between marginal and conditional distributions in their R Journal article, Generalized Mosaic Plots in the ggplot2 Framework.
For a research analysis, write down the categories and the observations being counted before plotting. A useful figure caption identifies the variables, the count total and any aggregation. The CASRAI guide to reading contingency tables and their margins provides background for checking those quantities. The workflow below keeps the underlying table visible so the graph can be checked against it.
The example uses R’s HairEyeColor dataset. Its documentation describes 592 observations in a four-by-four-by-two array: four hair categories, four eye categories and two sex categories. It also explains that the sex subdivision was added for teaching. Use it to learn the plotting workflow; that added subdivision should not be presented as an independently collected demographic result.
How to install or access R
Download R through the CRAN mirror link on the R Project’s official site, choosing the route for your operating system. R supports Windows, macOS and UNIX platforms. For an operating-system walkthrough, see installing R and RStudio.
The main example uses functions from R’s standard packages: graphics, datasets, base and stats. It does not require installing a contributed plotting package. Run the commands in an R session and keep their printed tables alongside the figure.
Use explicit package names when comparing implementations. graphics::mosaicplot(), vcd::mosaic() and regclass::mosaic() have different interfaces. A tutorial calling mosaic() is therefore not automatically describing the base-R function. Read the help page for the particular function you intend to use:
help("mosaicplot", package = "graphics")
help("xtabs", package = "stats")
How to create a mosaic plot in R step by step
This walkthrough converts a documented frequency array into a data frame, rebuilds a two-way count table and plots it. Keeping the conversion explicit makes it easier to adapt the example to a research file that already contains frequencies.
- Load the example and inspect its frequency column.
data("HairEyeColor", package = "datasets") d = as.data.frame(HairEyeColor) head(d) dim(HairEyeColor) sum(d$Freq)The
as.data.frame.tablemethod usesFreqas its default count-column name. Each row describes a combination of levels, rather than one student. The total ofFreqis 592; the array dimensions are 4, 4 and 2. These two checks establish what the rows mean before any plotting choices enter the analysis. - Rebuild the table by summing counts.
tab = stats::xtabs(Freq ~ Hair + Eye, data = d) tab sum(tab) dim(tab)In
xtabs(), the left side supplies values to sum and the right side supplies the grouping variables. Omitting Sex here aggregates its two levels, leaving a four-by-four Hair-by-Eye table. The observation total remains 592. Name the resulting object and reuse it for both plotting and diagnostic calculations. - Draw the initial mosaicplot in R.
graphics::mosaicplot( tab, main = "Hair and eye categories", xlab = "Hair", ylab = "Eye", color = TRUE, las = 1 )Use the category labels to locate each cell, then compare the rectangles with the printed table. Keep this first view descriptive: its fill distinguishes parts of the display. Add residual shading separately so you can explain the change in the caption.
- Add shading against the independence model.
graphics::mosaicplot( tab, main = "Hair and eye categories: independence residuals", shade = TRUE, type = "pearson", las = 1 )The base function defaults to an independence model. Setting
shade = TRUEactivates residual shading;colorcontrols ordinary fill when shading is off. Avoid describing the shaded colors as merely category colors. - Inspect the corresponding numerical quantities.
fit = stats::chisq.test(tab) fit$observed fit$expected fit$residuals fit$stdres fit$p.valueThe returned fields distinguish observed counts, expected counts, Pearson residuals and standardized residuals. Keep their names in your analysis notes. If an explanation refers to a particular residual, identify which field it uses rather than treating both fields as interchangeable.
Individual records versus frequency rows
For a file with one observation per row, table() counts combinations directly. For the frequency data frame above, those same-looking commands answer a different question:
wrong_for_counts = table(d$Hair, d$Eye)
sum(wrong_for_counts)
sum(tab)
The first total is 32: four hair levels × four eye levels × two sex levels. The second is 592 because it sums the documented frequencies. Each Hair-by-Eye combination occurs in two frequency rows, so counting rows loses the original cell counts. This is a concrete way to audit a figure that appears balanced despite unequal underlying frequencies.
With your own individual-record data, substitute the relevant category columns into table(). With an existing frequency column, substitute its name on the left of xtabs(). Do not change between these representations without checking the total.
There is also a direct formula route for the original array:
graphics::mosaicplot(~ Hair + Eye, data = HairEyeColor,
shade = TRUE)
For a table input, the formula selects dimensions and the function computes the corresponding marginal table. Keep the left side empty. This differs from handing it the frequency data frame d, where the variables would be cross-tabulated as records. Explicitly building tab remains useful when you want to inspect and reuse the exact counts.
How to read the output
Read area, within-group height and shading as separate encodings. The R documentation for spineplot() describes the two-variable geometry: group widths reflect marginal frequencies, and segment heights reflect conditional frequencies. Multiplying those proportions gives a cell’s joint proportion. A tall tile in a narrow group can therefore represent fewer observations than a shorter tile in a wide group.
Compare heights within the same group when your question concerns its composition. Compare areas when your question concerns how many observations occupy a category combination. Comparing heights alone across groups silently ignores their differing sizes. Retain the table when exact counts matter; a plotted rectangle is a visual summary rather than a numeric label.
Residual shading and model interpretation
For base R’s shaded display, positive residuals use blue with solid borders, and negative residuals use red with broken borders. The default absolute cut points are 2 and 4. Report these as the display’s residual bands; do not turn a colored tile into a standalone statement about the whole association.
The chisq.test() documentation defines Pearson residuals as (observed - expected) / sqrt(expected). Its stdres field uses a different residual variance. Its test output also provides an overall statistic and p-value. The CASRAI guide to chi-square testing in R explains that separate inferential step. Make the table and model explicit when reporting the shaded figure.
Three-way mosaic plots in R
R also supports mosaics with more than two categorical variables. The unaggregated HairEyeColor example retains Sex as another split. Decide whether your question concerns the collapsed Hair-by-Eye distribution or the three-way structure before choosing the figure. The dataset’s teaching-related subdivision remains relevant when explaining either display.
The vcd reference documents conditioning variables through condvars and model expectations through expected. Those options make the conditioning and model choices explicit. Do not interpret a conditional display as if it were the same analysis as an aggregated two-variable table.
Troubleshooting mosaic plots in R
Start with the table and its labels when a mosaic is empty, unexpectedly uniform or hard to interpret. Styling a count error makes that error harder to notice. The downloadable data table below compiles documented input and diagnostic checks across the tabulation, plotting and testing functions.
Missing observations and missing counts
For individual-record data, table(..., useNA = "ifany") can expose missing categories during inspection. The default excludes missing values. Decide how to handle them before creating the final analysis table, and record the resulting denominator.
For summarized data, distinguish a missing frequency from a missing category label. The xtabs() documentation separates those controls: na.rm addresses missing values on the left side, while addNA can create a separate level for missing factors. Treating a missing count as zero is an analysis decision, not a cosmetic fix.
Unused levels and zero margins
Unused factor levels can leave entire margins at zero. The xtabs() reference documents drop.unused.levels = TRUE for dropping unused levels and warns that zero margins prevent the subsequent independence test from working. Review why a category is empty before dropping it; distinguish an absent level from an observed zero combination.
Different orientation or difficult labels
Check variable order against the labels whenever you compare figures from different functions. The vcd manual explicitly notes that its default splitting orientation differs from graphics::mosaicplot(). A rotated arrangement is not by itself evidence that the counts changed.
If labeling drives your package choice, the DescTools reference documents PlotMosaic() specifically as an alternative to base labeling, with orientation, spacing and label controls. Its supported input is a two-way table. Confirm that restriction before handing it the original three-dimensional array.
Mixing mosaic functions
The regclass function accepts a response-style y ~ x formula and offers inside labels and optional equal widths. Its equal = TRUE changes the display so widths no longer encode group frequencies. Keep the package namespace visible in saved scripts, especially when adapting examples from different documentation pages.
Free alternatives to R mosaicplot
These documented alternatives cover related categorical displays. Choose by the interface and representation your analysis needs, then check the resulting table and legend. The table compares plotting capabilities; it does not reproduce the downloadable function-check dataset.
| Alternative | Documented use | Difference to check |
|---|---|---|
| R graphics::spineplot | Two-way table or explanatory-variable/response display | Emphasizes conditional segment heights and marginal group widths. |
| R vcd::mosaic | Extended mosaics with conditioning and model expectations | Uses grid graphics; default split orientation differs from base R. |
| R regclass::mosaic | Two categorical variables through y ~ x | Supports inside labels and an equal-width option. |
| R DescTools::PlotMosaic | Two-way contingency tables with label controls | Does not accept a higher-dimensional table directly. |
| Python statsmodels.graphics.mosaicplot.mosaic | Dictionary, Series, array or DataFrame inputs | Provides properties and labelizer callbacks for tile appearance and text. |
The statsmodels interface is useful when the surrounding analysis is in Python. Its documentation accepts nonnegative cell values and treats missing combinations of dictionary keys as zero. Check whether an omitted combination really means zero in your data before relying on that behavior. The function returns both the figure and a dictionary describing its tiles, which supports later annotation. Its statistical-color option is a separate implementation: preserve the model explanation and read its own legend rather than carrying R’s color conventions into a Python caption.
For an analysis already built around ggplot2, Jeppson and Hofmann’s article explains ggmosaic‘s geometry and weighted aesthetic mappings. The CASRAI introduction to building plots in R with ggplot2 covers that surrounding plotting framework. Keep the count-preserving checks above when translating a figure into another plotting system.
Sources
- R Project: The R Project for Statistical Computing, checked 2026-11-17.
- R graphics: Mosaic Plots, checked 2026-11-17.
- R base: Cross Tabulation and Table Creation, checked 2026-11-17.
- R stats: Cross Tabulation, checked 2026-11-17.
- R datasets: Hair and Eye Color of Statistics Students, checked 2026-11-17.
- R stats: Pearson’s Chi-squared Test for Count Data, checked 2026-11-17.
- vcd: Extended Mosaic Plots, checked 2026-11-17.
- R graphics: Spine Plots and Spinograms, checked 2026-11-17.
- regclass: Mosaic plot, checked 2026-11-17.
- DescTools: Mosaic Plots, checked 2026-11-17.
- statsmodels: statsmodels.graphics.mosaicplot.mosaic, checked 2026-11-17.
- Jeppson and Hofmann, The R Journal: Generalized Mosaic Plots in the ggplot2 Framework, checked 2026-11-17.
Data: R mosaic workflow: inputs and diagnostic checks
Original compilation of documented input representations, named controls and diagnostic outputs for four R functions used in a mosaic plotting workflow. Compiled across the R base, stats and graphics reference manuals; this is an API reference matrix, not empirical research data.
| Function | Documented input | Control or output to inspect | Documentation source |
|---|---|---|---|
| base::table | Cross-classifying factors or objects interpretable as factors | useNA: no, ifany or always | https://stat.ethz.ch/R-manual/R-devel/library/base/html/table.html |
| stats::xtabs | Formula with optional counts on the left and grouping factors on the right | drop.unused.levels: whether unused factor levels are dropped | https://stat.ethz.ch/R-manual/R-devel/library/stats/html/xtabs.html |
| graphics::mosaicplot | Contingency table or formula interface | shade activates residual shading; type selects pearson, deviance or FT | https://stat.ethz.ch/R-manual/R-devel/library/graphics/html/mosaicplot.html |
| stats::chisq.test | Two-dimensional contingency count table for an independence test | observed, expected, residuals and stdres are distinct returned fields | https://stat.ethz.ch/R-manual/R-devel/library/stats/html/chisq.test.html |
Sources
- R: Cross Tabulation and Table Creation (accessed 2026-11-17)
- R: Cross Tabulation (accessed 2026-11-17)
- R: Mosaic Plots (accessed 2026-11-17)
- R: Pearson's Chi-squared Test for Count Data (accessed 2026-11-17)
Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.







