| Title: | Mosaic Plots in the 'ggplot2' Framework, Extended |
| Version: | 0.5.1 |
| Date: | 2026-09-15 |
| Description: | Mosaic plots in the 'ggplot2' framework. Mosaic plot functionality is provided in a single 'ggplot2' layer by calling the geom 'mosaic'. This extends the now-defunct 'ggmosaic' package by allowing fitted loglinear models which can be used to show patterns of association among variables in frequency tables. |
| License: | GPL-2 | GPL-3 [expanded from: GPL (≥ 2)] |
| Language: | en-US |
| URL: | https://friendly.github.io/ggmosaic2/, https://github.com/friendly/ggmosaic2 |
| BugReports: | https://github.com/friendly/ggmosaic2/issues |
| Depends: | ggplot2 (≥ 4.0.0), R (≥ 4.1.0) |
| Imports: | productplots, dplyr, plotly (≥ 4.9.3), purrr, rlang, tidyr, ggrepel, scales, withr (≥ 2.5.0) |
| Suggests: | gridExtra, knitr, rmarkdown, shiny (≥ 1.1.0), patchwork, vcdExtra |
| VignetteBuilder: | knitr |
| Encoding: | UTF-8 |
| LazyData: | true |
| Config/roxygen2/version: | 8.1.0 |
| NeedsCompilation: | no |
| Packaged: | 2026-09-15 14:27:34 UTC; friendly |
| Author: | Michael Friendly |
| Maintainer: | Michael Friendly <friendly@yorku.ca> |
| Repository: | CRAN |
| Date/Publication: | 2026-09-16 12:30:02 UTC |
ggmosaic2: Mosaic Plots in the 'ggplot2' Framework, Extended
Description
Mosaic plots in the 'ggplot2' framework. Mosaic plot functionality is provided in a single 'ggplot2' layer by calling the geom 'mosaic'. This extends the now-defunct 'ggmosaic' package by allowing fitted loglinear models which can be used to show patterns of association among variables in frequency tables.
Author(s)
Maintainer: Michael Friendly friendly@yorku.ca (ORCID) [copyright holder]
Authors:
Michael Friendly friendly@yorku.ca (ORCID) [copyright holder]
Gavin Klorfine gklorfin@yorku.ca (ORCID)
Haley Jeppson hjeppson@iastate.edu (ORCID)
Heike Hofmann hofmann@iastate.edu (ORCID)
Di Cook dicook@monash.edu (ORCID)
Other contributors:
Hadley Wickham hadley@posit.co (ORCID) [contributor]
See Also
Useful links:
Report bugs at https://github.com/friendly/ggmosaic2/issues
Geom proto
Description
Geom proto
Value
A ggproto object inheriting from ggplot2::Geom, used
internally by geom_mosaic() to draw the mosaic tile rectangles. Not
intended to be called directly.
Geom proto
Description
Geom proto
Value
A ggproto object inheriting from ggplot2::Geom, used
internally by geom_mosaic_jitter() to draw jittered points within
mosaic plot cells. Not intended to be called directly.
Geom proto
Description
Geom proto
Value
A ggproto object inheriting from ggplot2::Geom, used
internally by geom_mosaic_text() to draw text/label annotations on
mosaic plot cells. Not intended to be called directly.
Geom proto
Description
Geom proto
Value
A ggproto object inheriting from ggplot2::Stat, used
internally by stat_mosaic() (and geom_mosaic()) to compute the
rectangle boundaries and cell statistics for a mosaic plot layer. Not
intended to be called directly.
Geom proto
Description
Geom proto
Value
A ggproto object inheriting from ggplot2::Stat, used
internally by stat_mosaic_jitter() (and geom_mosaic_jitter()) to
compute jittered point positions for a mosaic plot layer. Not intended
to be called directly.
Geom proto
Description
Geom proto
Value
A ggproto object inheriting from ggplot2::Stat, used
internally by stat_mosaic_text() (and geom_mosaic_text()) to
compute label positions for a mosaic plot layer. Not intended to be
called directly.
Build model formula from user specification
Description
Build model formula from user specification
Usage
build_model_formula(expected, vars, conds = NULL, variable_labels = NULL)
Arguments
expected |
Formula, character shortcut, or NULL |
vars |
Character vector of margin variable names (with prefixes like x__Class) |
conds |
Character vector of conditioning variable names (optional, with prefixes) |
variable_labels |
Optional named character vector mapping internal variable names to their original expressions. |
Value
Formula object or NULL
Template for a double decker plot. A double decker plot is composed of a sequence of spines in the same direction, with the final spine in the opposite direction.
Description
Template for a double decker plot. A double decker plot is composed of a sequence of spines in the same direction, with the final spine in the opposite direction.
Usage
ddecker(direction = "h")
Arguments
direction |
direction of first split |
Value
A function of one argument, the number of splits n, that returns
a character vector of divider function names ("hspine"/"vspine") to
apply at each split – suitable for the divider argument of
geom_mosaic() and related layers.
Examples
data(titanic)
ggplot(data = titanic, aes(x = product(Class, Sex))) +
geom_mosaic(divider = ddecker("v"))
Facet mosaic plots with panel-specific axes
Description
facet_mosaic_grid() lays panels out like ggplot2::facet_grid(), but gives
every panel its own x and y position scales. Mosaic category breaks depend on
the proportions calculated inside a panel, so sharing a position scale can
place one panel's ticks and labels on another panel's mosaic.
Usage
facet_mosaic_grid(
rows = NULL,
cols = NULL,
space = "fixed",
shrink = TRUE,
labeller = "label_value",
as.table = TRUE,
switch = NULL,
drop = TRUE,
margins = FALSE,
axes = "all",
axis.labels = "all"
)
Arguments
rows, cols |
A set of variables or expressions quoted by
For compatibility with the classic interface, |
space |
If |
shrink |
If |
labeller |
A function that takes one data frame of labels and
returns a list or data frame of character vectors. Each input
column corresponds to one factor. Thus there will be more than
one with |
as.table |
If |
switch |
By default, the labels are displayed on the top and
right of the plot. If |
drop |
If |
margins |
Either a logical value or a character
vector. Margins are additional facets which contain all the data
for each of the possible values of the faceting variables. If
|
axes |
Determines which axes will be drawn. When |
axis.labels |
Determines whether to draw labels for interior axes when
the |
Details
Panel widths and heights remain fixed. By default, axes and their labels are
drawn for every panel so that each panel's category positions are visible.
The panel-specific label positions are retained with theme_mosaic(); that
theme intentionally hides the tick marks themselves.
Value
A Facet object that can be added to a ggplot.
Author(s)
Gavin Klorfine
Examples
facet_data <- expand.grid(
period = factor(c("Before", "After")),
group = factor(c("A", "B")),
response = factor(c("No", "Yes"))
)
facet_data$n <- c(30, 10, 20, 40, 10, 35, 40, 15)
ggplot(facet_data,
aes(weight = n, x = product(response, group), fill = response)) +
geom_mosaic() +
facet_mosaic_grid(cols = vars(period))
Fit Poisson GLM and calculate Pearson residuals
Description
Fit Poisson GLM and calculate Pearson residuals
Usage
fit_loglinear_model(data, vars, model_formula)
Arguments
data |
Data frame with .n column (observed counts) |
vars |
Character vector of all variable names (margins + conds) |
model_formula |
Formula for the GLM |
Value
Data frame with added .expected and .residual columns
Flying Etiquette Survey Data
Description
Data from the results of a SurveyMonkey survey commissioned by FiveThirtyEight for the story 41 Percent of Fliers Say It’s Rude To Recline Your Airplane Seat.
Usage
fly
Format
A data frame with 1040 rows and 27 variables:
- id
Respondent ID
- flight_freq
How often do you travel by plane?
- do_you_recline
Do you ever recline your seat when you fly?
- height
How tall are you?
- has_child_under_18
Do you have any children under 18?
- three_seats_two_arms
n a row of three seats, who should get to use the two arm rests?
- two_seats_one_arm
In a row of two seats, who should get to use the middle arm rest?
- window_shade
Who should have control over the window shade?
- rude_to_move_to_unsold_seat
Is it rude to move to an unsold seat on a plane?
- rude_to_talk_to_neighbor
Generally speaking, is it rude to say more than a few words to the stranger sitting next to you on a plane?
- six_hr_flight_leave_seat
On a six hour flight from NYC to LA, how many times is it acceptable to get up if you're not in an aisle seat?
- reclining_obligation_to_behind
Under normal circumstances, does a person who reclines their seat during a flight have any obligation to the person sitting behind them?
- rude_to_recline
Is it rude to recline your seat on a plane?
- eliminate_reclining
Given the opportunity, would you eliminate the possibility of reclining seats on planes entirely?
- rude_to_switch_seats_friends
Is it rude to ask someone to switch seats with you in order to be closer to friends?
- rude_to_switch_seats_family
Is it rude to ask someone to switch seats with you in order to be closer to family?
- rude_to_wake_neighbor_bathroom
Is it rude to wake a passenger up if you are trying to go to the bathroom?
- rude_to_wake_neighbor_walk
Is it rude to wake a passenger up if you are trying to walk around?
- rude_to_bring_baby
In general, is it rude to bring a baby on a plane?
- rude_to_bring_unruly_child
In general, is it rude to knowingly bring unruly children on a plane?
- use_electronics_takeoff
Have you ever used personal electronics during take off or landing in violation of a flight attendant's direction?
- smoked_inflight
Have you ever smoked a cigarette in an airplane bathroom when it was against the rules?
- gender
Gender
- age
Age
- household_income
Household Income
- education
Education
- region
Region
Source
https://github.com/fivethirtyeight/data/tree/master/flying-etiquette-survey
Mosaic plots.
Description
A mosaic plot is a convenient graphical summary of the conditional distributions in a contingency table and is composed of spines in alternating directions.
Usage
geom_mosaic(
mapping = NULL,
data = NULL,
stat = "mosaic",
position = "identity",
na.rm = FALSE,
divider = mosaic(),
offset = 0.01,
show.legend = NA,
inherit.aes = TRUE,
expected = NULL,
...
)
stat_mosaic_text(
mapping = NULL,
data = NULL,
geom = "Text",
position = "identity",
na.rm = FALSE,
divider = mosaic(),
show.legend = NA,
inherit.aes = TRUE,
offset = 0.01,
expected = NULL,
...
)
stat_mosaic(
mapping = NULL,
data = NULL,
geom = "mosaic",
position = "identity",
na.rm = FALSE,
divider = mosaic(),
show.legend = NA,
inherit.aes = TRUE,
offset = 0.01,
expected = NULL,
...
)
Arguments
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 |
divider |
Divider function. The default divider function is mosaic() which will use spines in alternating directions. The four options for partitioning:
When omitted, |
offset |
Set the fixed gap at the deepest split. Gaps increase by a
factor of 1.5 toward the outermost split. When omitted, the value can be
inherited from |
show.legend |
logical. Should this layer be included in the legends?
|
inherit.aes |
If |
expected |
Optional specification for loglinear model residual shading.
Can be a formula (e.g., |
... |
other arguments passed on to |
geom |
The geometric object to use to display the data for this layer.
When using a
|
Details
Variables mapped only to fill or alpha retain their historical
role as innermost mosaic partitions, but they are not shown on the automatic
product axes. Position axes label only variables explicitly mapped through
x or conds. If an aesthetic variable is also included in product(), it
remains eligible for an axis label.
Product variables are ordered from innermost to outermost. With the default
mosaic divider, reversing two variables swaps their horizontal and vertical
roles; for example, product(predictions, actual) places actual
on the primary x axis.
Value
A ggplot2 layer that can be added to a plot.
Computed variables
- x
location of center of the rectangle
- y
location of center of the rectangle
- xmin
location of bottom left corner
- xmax
location of bottom right corner
- ymin
location of top left corner
- ymax
location of top right corner
Author(s)
Gavin Klorfine
Examples
data(titanic)
ggplot(data = titanic, aes(x = product(Class), fill = Survived)) +
geom_mosaic()
# good practice: use the 'dependent' variable (or most important variable)
# as fill variable
# if there is only one variable inside `product()`,
# `product()` can be omitted
ggplot(data = titanic, aes(x = Class, fill = Survived)) +
geom_mosaic()
ggplot(data = titanic,
aes(x = product(Class, Age), fill = Survived)) +
geom_mosaic()
ggplot(data = titanic,
aes(x = product(Class), conds = product(Age), fill = Survived)) +
geom_mosaic()
# if there is only one variable inside `product()`,
# `product()` can be omitted
ggplot(data = titanic, aes(x = Class, conds = Age, fill = Survived)) +
geom_mosaic()
ggplot(data = titanic,
aes(x = product(Survived, Class), fill = Age)) +
geom_mosaic()
# Variables can be transformed directly inside mosaic aesthetics
ggplot(data = mtcars,
aes(x = product(factor(gear)), fill = factor(cyl))) +
geom_mosaic()
# A fill-only variable colours and partitions the tiles without appearing on
# a position axis. Reverse the product order to put `actual` on the x axis.
set.seed(19790801)
predictions <- sample(iris$Species)
confusion <- as.data.frame(table(actual = iris$Species, predictions))
confusion$is_correct <- ifelse(
confusion$actual == confusion$predictions,
"Correct prediction", "Incorrect prediction"
)
ggplot(confusion, aes(
weight = Freq,
x = product(predictions, actual),
fill = is_correct
)) +
geom_mosaic()
# Wrapped in donttest: still runs under R CMD check --run-donttest and is
# exercised by the package's tests to make sure it works.
data(happy)
ggplot(data = happy, aes(x = product(happy))) +
geom_mosaic(divider = "hbar")
ggplot(data = happy, aes(x = product(happy))) +
geom_mosaic() +
coord_flip()
# weighting is important
ggplot(data = happy, aes(weight = wtssall, x = product(happy))) +
geom_mosaic()
ggplot(data = happy,
aes(weight = wtssall, x = product(health), fill = happy)) +
geom_mosaic() +
theme(axis.text.x=element_text(angle=35))
ggplot(data = happy,
aes(weight = wtssall, x = product(health), fill = happy)) +
geom_mosaic(na.rm = TRUE)
ggplot(data = happy,
aes(weight = wtssall, x = product(health, sex, degree), fill = happy)) +
geom_mosaic(na.rm = TRUE)
# here is where a bit more control over the spacing of the bars is helpful:
# set labels manually:
ggplot(data = happy,
aes(weight = wtssall, x = product(age), fill = happy)) +
geom_mosaic(na.rm = TRUE, offset = 0) +
scale_x_productlist("Age", labels=c(17+1:72))
# thin out labels manually:
labels <- c(17+1:72)
labels[labels %% 5 != 0] <- ""
ggplot(data = happy,
aes(weight = wtssall, x = product(age), fill = happy)) +
geom_mosaic(na.rm = TRUE, offset = 0) +
scale_x_productlist("Age", labels=labels)
ggplot(data = happy,
aes(weight = wtssall, x = product(age), fill = happy,
conds = product(sex))) +
geom_mosaic(divider = mosaic("v"), na.rm = TRUE, offset = 0.001) +
scale_x_productlist("Age", labels=labels)
ggplot(data = happy,
aes(weight = wtssall, x = product(age), fill = happy)) +
geom_mosaic(na.rm = TRUE, offset = 0) +
facet_grid(sex~.) +
scale_x_productlist("Age", labels=labels)
ggplot(data = happy,
aes(weight = wtssall, x = product(happy, finrela, health))) +
geom_mosaic(divider = mosaic("h"))
ggplot(data = happy,
aes(weight = wtssall, x = product(happy, finrela, health))) +
geom_mosaic(offset = .005)
# Spine example
ggplot(data = happy,
aes(weight = wtssall, x = product(health), fill = health)) +
geom_mosaic() +
facet_grid(happy~.)
# Residual shading with independence model
ggplot(data = titanic, aes(x = product(Class, Sex))) +
geom_mosaic(expected = "independence") +
scale_fill_residual()
# Custom model formula
ggplot(data = titanic, aes(x = product(Class, Sex, Survived))) +
geom_mosaic(expected = ~ Class + Sex) +
scale_fill_residual()
# end of donttest
Jittered dots in Mosaic plots.
Description
A mosaic plat with jittered dots
Usage
geom_mosaic_jitter(
mapping = NULL,
data = NULL,
stat = "mosaic_jitter",
position = "identity",
na.rm = FALSE,
divider = mosaic(),
offset = 0.01,
drop_level = FALSE,
seed = NA,
show.legend = NA,
inherit.aes = TRUE,
...
)
stat_mosaic_jitter(
mapping = NULL,
data = NULL,
geom = "mosaic_jitter",
position = "identity",
na.rm = FALSE,
divider = mosaic(),
show.legend = NA,
inherit.aes = TRUE,
offset = 0.01,
drop_level = FALSE,
seed = NA,
...
)
Arguments
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 |
divider |
Divider function. The default divider function is mosaic() which will use spines in alternating directions. The four options for partitioning:
When omitted, |
offset |
Set the fixed gap at the deepest split. Gaps increase by a
factor of 1.5 toward the outermost split. When omitted, the value can be
inherited from |
drop_level |
Generate points for the max - 1 level |
seed |
Random seed passed to |
show.legend |
logical. Should this layer be included in the legends?
|
inherit.aes |
If |
... |
other arguments passed on to |
geom |
The geometric object to use to display the data for this layer.
When using a
|
Details
Variables mapped only to fill, alpha, or colour remain
available to the mosaic calculation and point aesthetics, but are not shown
on automatic product axes. Position axes label only variables explicitly
mapped through x or conds.
Value
A ggplot2 layer that can be added to a plot.
Computed variables
- xmin
location of bottom left corner
- xmax
location of bottom right corner
- ymin
location of top left corner
- ymax
location of top right corner
Author(s)
Gavin Klorfine
Examples
data(titanic)
ggplot(data = titanic, aes(x = product(Class))) +
geom_mosaic(aes(fill = Survived), alpha = 0.3) +
geom_mosaic_jitter(aes(color = Survived))
ggplot(data = titanic, aes(x = product(Class))) +
geom_mosaic(alpha = 0.1) +
geom_mosaic_jitter(aes(color = Survived), drop_level = TRUE)
ggplot(data = titanic, aes(x = product(Class, Sex))) +
mosaic_settings(divider = c("vspine", "hspine", "hspine")) +
geom_mosaic(alpha = 0.3, aes(fill = Survived)) +
geom_mosaic_jitter(aes(color = Survived))
ggplot(data = titanic,
aes(x = product(Class), conds = product(Sex), fill = Survived)) +
geom_mosaic(alpha = 0.3,
divider = c("vspine", "hspine", "hspine")) +
geom_mosaic_jitter(
divider = c("vspine", "hspine", "hspine"))
Labeling for Mosaic plots.
Description
A mosaic plot with text or labels
Usage
geom_mosaic_text(
mapping = NULL,
data = NULL,
stat = "mosaic",
position = "identity",
na.rm = FALSE,
divider = mosaic(),
offset = 0.01,
show.legend = NA,
inherit.aes = TRUE,
as.label = FALSE,
repel = FALSE,
repel_params = NULL,
check_overlap = FALSE,
display_values = "label",
format_digits = 1,
expected = NULL,
...
)
Arguments
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 |
divider |
Divider function. The default divider function is mosaic() which will use spines in alternating directions. The four options for partitioning:
When omitted, |
offset |
Set the fixed gap at the deepest split. Gaps increase by a
factor of 1.5 toward the outermost split. When omitted, the value can be
inherited from |
show.legend |
logical. Should this layer be included in the legends?
|
inherit.aes |
If |
as.label |
Show as a ggplot label (box with round corners) |
repel |
Use ggrepel so labels don't overlap |
repel_params |
List of ggrepel parameters (e.g. list(point.padding = 0)) |
check_overlap |
If |
display_values |
Character string specifying what values to display in cells.
Options: "label" (default, factor labels), "observed" (observed counts),
"expected" (expected values from model), "residual" (Pearson residuals).
"expected" and "residual" require a model supplied directly through
|
format_digits |
Number of decimal places for formatting numeric values (default: 1). Only used when display_values is not "label". |
expected |
Optional loglinear model specification (same as in |
... |
other arguments passed on to |
Value
A ggplot2 layer that can be added to a plot.
Author(s)
Gavin Klorfine
Examples
data(titanic)
ggplot(data = titanic, aes(x = product(Class), fill = Survived)) +
geom_mosaic() +
geom_mosaic_text()
ggplot(data = titanic, aes(x = product(Class, Sex), fill = Survived)) +
mosaic_settings(divider = c("vspine", "hspine", "hspine")) +
geom_mosaic() +
geom_mosaic_text(size = 2)
ggplot(data = happy, aes(x = product(happy, health), fill = happy)) +
geom_mosaic(aes(x = product(health)), na.rm = TRUE, show.legend = FALSE) +
geom_mosaic_text(na.rm = TRUE, show.legend = FALSE)
# avoid overlapping text
ggplot(data = happy, aes(x = product(happy, health), fill = happy)) +
geom_mosaic(aes(x = product(health)), na.rm = TRUE, show.legend = FALSE) +
geom_mosaic_text(na.rm = TRUE, check_overlap = TRUE, show.legend = FALSE)
# or use ggrepel
ggplot(data = happy, aes(x = product(happy, health), fill = happy)) +
geom_mosaic(aes(x = product(health)), na.rm = TRUE, show.legend = FALSE) +
geom_mosaic_text(na.rm = TRUE, repel = TRUE, show.legend = FALSE)
# and as a label
ggplot(data = happy, aes(x = product(happy, health), fill = happy)) +
geom_mosaic(aes(x = product(health)), na.rm = TRUE, show.legend = FALSE) +
geom_mosaic_text(
na.rm = TRUE, repel = TRUE, as.label = TRUE,
fill = "white", show.legend = FALSE
)
# Display observed counts in cells
ggplot(data = titanic, aes(x = product(Class, Sex))) +
geom_mosaic(aes(fill = Survived)) +
geom_mosaic_text(display_values = "observed")
# Display residuals with one shared model specification
ggplot(data = titanic, aes(x = product(Class, Sex))) +
mosaic_settings(expected = "independence") +
geom_mosaic() +
scale_fill_residual() +
geom_mosaic_text(display_values = "residual",
format_digits = 2)
# Display expected values
ggplot(data = titanic, aes(x = product(Class, Sex))) +
mosaic_settings(expected = "independence") +
geom_mosaic() +
scale_fill_residual() +
geom_mosaic_text(display_values = "expected",
format_digits = 1)
Launch shiny app (deprecated)
Description
Shiny app "EDA with Mosaic Plots" for interactive exploratory model building.
Usage
ggmosaic_app(example = c("mosaics", "models"), ...)
Arguments
example |
Selected shiny app to launch. |
... |
arguments passed on. |
Details
Deprecated. Inherited as-is from the original ggmosaic package and kept only for the
historical record. It is not maintained, and currently cannot find its app directory because
system.file() still looks up the old ggmosaic package name rather than ggmosaic2.
Value
Called for its side effect of launching a Shiny app; returns the
result of shiny::runApp().
Examples
## Not run:
# Deprecated and currently non-functional; see Details.
ggmosaic_app("mosaics")
## End(Not run)
Data related to happiness from the general social survey.
Description
The data is a small sample of variables related to happiness from the general social survey (GSS). The GSS is a yearly cross-sectional survey of Americans, run since 1972. We combine data for more than 25 years to yield over 60 thousand observations, and of the over 5,000 variables, we select some variables that are related to happiness:
Usage
data(happy)
Format
A data frame with 62466 rows and 11 variables
year. year of the response, 1972 to 2018.
age. age in years: 18–89 (89 stands for all 89 year olds and older).
degree. highest education: lt high school, high school, junior college, bachelor, graduate.
finrela. how is your financial status compared to others: far below, below average, average, above average, far above.
happy. happiness: very happy, pretty happy, not too happy.
health. health: excellent, good, fair, poor.
marital. marital status: married, never married, divorced, widowed, separated.
sex. sex: female, male.
polviews. from extremely conservative to extremely liberal.
partyid. party identification: strong republican, not str republican, ind near rep, independent, ind near dem, not str democrat, strong democrat, other party.
wtssall. probability weight. 0.39–8.74
Horizontal bar partition: width constant, height varies.
Description
Horizontal bar partition: width constant, height varies.
Usage
hbar(data, bounds, offset = 0.02, max = NULL)
Arguments
data |
bounds data frame |
bounds |
bounds of space to partition |
offset |
space between spines |
max |
maximum value |
Value
A data frame of rectangle boundaries (l, r, b, t), one row
per level of data.
Examples
data(titanic)
ggplot(data = titanic, aes(x = product(Class))) +
geom_mosaic(divider = "hbar")
Horizontal spine partition: height constant, width varies.
Description
Horizontal spine partition: height constant, width varies.
Usage
hspine(data, bounds, offset = offset, max = NULL)
Arguments
data |
bounds data frame |
bounds |
bounds of space to partition |
offset |
space between spines |
max |
maximum value |
Value
A data frame of rectangle boundaries (l, r, b, t), one row
per level of data.
Examples
data(titanic)
ggplot(data = titanic, aes(x = product(Class))) +
geom_mosaic(divider = "hspine")
Template for a mosaic plot. A mosaic plot is composed of spines in alternating directions.
Description
Template for a mosaic plot. A mosaic plot is composed of spines in alternating directions.
Usage
mosaic(direction = "h")
Arguments
direction |
direction of first split |
Value
A function of one argument, the number of splits n, that returns
a character vector of divider function names ("hspine"/"vspine") to
apply at each split – suitable for the divider argument of
geom_mosaic() and related layers.
Examples
data(titanic)
ggplot(data = titanic, aes(x = product(Class, Sex))) +
geom_mosaic(divider = mosaic("v"))
Settings for mosaic plot layers
Description
Set the divider, gap size, and model used to calculate expected frequencies for mosaic layers in a plot. A value set directly in a layer takes priority.
Usage
mosaic_settings(divider, offset, expected)
Arguments
divider |
A divider function, a character vector naming divider functions, or a list of divider functions. |
offset |
A single non-negative number giving the gap at the deepest split. Gaps increase by a factor of 1.5 toward the outermost split. |
expected |
The log-linear model used to calculate expected frequencies
and Pearson residuals. Supply a formula or one of |
Details
A layer inherits a setting only when its corresponding argument is omitted.
Settings are resolved in this order: an explicitly supplied layer argument
(including expected = NULL), the plot's mosaic_settings() value, and the
layer default (mosaic(), 0.01, or NULL).
divider and offset are inherited by geom_mosaic(), stat_mosaic(),
geom_mosaic_text(), stat_mosaic_text(), geom_mosaic_jitter(), and
stat_mosaic_jitter(). expected is inherited by the same constructors
except the mosaic-jitter geom and stat.
The position of mosaic_settings() among the layers in a plot has no
effect. If it is added more than once, the last supplied value for each
setting is used; omitted arguments do not change earlier settings.
Settings are local to the plot and do not change package or session defaults.
They share configuration, not computations or fitted model objects, between
layers.
Value
An object of class "ggmosaic_settings" that can be added to a
ggplot with +.
Author(s)
Gavin Klorfine
See Also
geom_mosaic(), stat_mosaic(), geom_mosaic_text(),
stat_mosaic_text(), geom_mosaic_jitter(), stat_mosaic_jitter(),
mosaic(), and ddecker()
Examples
data(titanic)
ggplot(titanic, aes(x = product(Class, Sex))) +
mosaic_settings(
expected = "independence",
divider = c("vspine", "hspine"),
offset = 0.005
) +
geom_mosaic() +
geom_mosaic_text(display_values = "residual") +
scale_fill_residual() +
theme_mosaic()
# An explicit layer argument overrides the plot setting. Here NULL turns
# model fitting off for the mosaic layer.
ggplot(titanic, aes(x = product(Class, Sex), fill = Survived)) +
mosaic_settings(expected = "independence") +
geom_mosaic(expected = NULL)
Calculate frequencies.
Description
Calculate frequencies.
Usage
prodcalc(
data,
formula,
divider = mosaic(),
cascade = 0,
scale_max = TRUE,
na.rm = FALSE,
offset = 0.01,
expected = NULL,
variable_labels = NULL
)
Arguments
data |
input data frame |
formula |
formula specifying display of plot |
divider |
divider function |
cascade |
cascading amount, per nested layer |
scale_max |
Logical vector of length 1. If |
na.rm |
Logical vector of length 1 - should missing levels be silently removed? |
offset |
Numeric value specifying the fixed gap at the deepest split (default: 0.01). Gaps increase by a factor of 1.5 toward the outermost split. |
expected |
Optional. Specification for loglinear model to calculate residuals. Can be:
When specified, adds |
variable_labels |
Optional named character vector mapping internal variable names to the expressions shown to users. Used internally by the ggplot2 layer wrappers. |
Value
A data frame giving rectangle boundaries (l, r,
b, t) and computed frequencies for each partition/cell,
plus .expected/.residual columns when expected is
supplied.
Examples
data(happy)
prodcalc(happy, ~ happy, "hbar", offset = 0.005)
prodcalc(happy, ~ happy, "hspine", offset = 0.01)
Wrapper for a list
Description
Wrapper for a list
Usage
product(...)
Arguments
... |
Unquoted variables going into the product plot. |
Value
A list of expressions (see rlang::exprs()), one per argument,
used inside aes() to mark the variables that define the mosaic's
product formula.
Examples
data(titanic)
ggplot(data = titanic,
aes(x = product(Survived, Class), fill = Survived)) +
geom_mosaic()
Diverging color scale for Pearson residuals
Description
Provides a red-white-blue color scale centered at 0 for visualizing
Pearson residuals from loglinear models. Designed for use with
geom_mosaic() when a model is supplied through the layer's
expected argument or through mosaic_settings.
Usage
scale_fill_residual(
...,
low = "darkred",
mid = "white",
high = "darkblue",
midpoint = 0,
limits = NULL,
name = "Pearson\nResidual"
)
scale_fill_residuals(
...,
low = "darkred",
mid = "white",
high = "darkblue",
midpoint = 0,
limits = NULL,
name = "Pearson\nResidual"
)
Arguments
... |
Arguments passed to |
low |
Color for negative residuals (default: "darkred") |
mid |
Color for zero residuals (default: "white") |
high |
Color for positive residuals (default: "darkblue") |
midpoint |
Center point for color scale (default: 0) |
limits |
Range used for the color gradient. Values beyond supplied limits receive the corresponding endpoint color. |
name |
Legend title |
Details
The default legend always labels -4, 0, and 4. It also labels
supplied limits and the observed minimum and maximum when those differ
from the limits. The legend extends to every labeled value, with solid
endpoint color beyond supplied limits. When the contributing mosaic cells
have outlines, positive residuals have a solid dark blue outline, negative
residuals have a dashed dark red outline, and an unoutlined midpoint band
(white by default) separates them at zero. Setting colour = NA on every
contributing mosaic layer removes these outlines from both the cells and
the legend. Black ticks are drawn outside the color bar, which stretches
with the mosaic panel. Nearby vertical labels are separated, and a thin
elbow connects each displaced label to its exact tick. The neighboring
label uses a longer straight tick so nearby text shares a common alignment.
Automatically generated numeric labels are rounded to one decimal place.
The legend can be hidden normally with
theme(legend.position = "none").
Value
A ggplot2 fill scale that can be added to a plot.
Author(s)
Gavin Klorfine
Examples
data(titanic)
# Independence model with residual shading
ggplot(data = titanic, aes(x = product(Class, Sex))) +
geom_mosaic(expected = "independence") +
scale_fill_residual()
# Custom colors
ggplot(data = titanic, aes(x = product(Class, Sex))) +
geom_mosaic(expected = "independence") +
scale_fill_residual(low = "red", high = "blue")
# Custom limits to highlight strong deviations
ggplot(data = titanic, aes(x = product(Class, Sex, Survived))) +
geom_mosaic(expected = ~ Class + Sex) +
scale_fill_residual(limits = c(-4, 4))
Helper function for determining scales
Description
Used internally to determine class of variable x
Usage
## S3 method for class 'productlist'
scale_type(x)
Arguments
x |
variable |
Value
character string "productlist"
Determining scales for mosaics
Description
Determining scales for mosaics
Usage
scale_x_productlist(
name = ggplot2::waiver(),
breaks = product_breaks(),
minor_breaks = NULL,
labels = product_labels(),
limits = NULL,
expand = ggplot2::waiver(),
oob = scales::censor,
na.value = NA_real_,
transform = "identity",
position = "bottom",
sec.axis = ggplot2::waiver()
)
scale_y_productlist(
name = ggplot2::waiver(),
breaks = product_breaks(),
minor_breaks = NULL,
labels = product_labels(),
limits = NULL,
expand = ggplot2::waiver(),
oob = scales::censor,
na.value = NA_real_,
transform = "identity",
position = "left",
sec.axis = ggplot2::waiver()
)
ScaleContinuousProduct
Arguments
name |
set to pseudo waiver function |
breaks |
One of:
|
minor_breaks |
One of:
|
labels |
One of the options below. Please note that when
|
limits |
One of:
|
expand |
For position scales, a vector of range expansion constants used to add some
padding around the data to ensure that they are placed some distance
away from the axes. Use the convenience function |
oob |
One of:
|
na.value |
Missing values will be replaced with this value. |
transform |
For continuous scales, the name of a transformation object or the object itself. Built-in transformations include "asn", "atanh", "boxcox", "date", "exp", "hms", "identity", "log", "log10", "log1p", "log2", "logit", "modulus", "probability", "probit", "pseudo_log", "reciprocal", "reverse", "sqrt" and "time". A transformation object bundles together a transform, its inverse,
and methods for generating breaks and labels. Transformation objects
are defined in the scales package, and are called |
position |
For position scales, The position of the axis.
|
sec.axis |
specify a secondary axis. By default, category labels for
the inner variables of the mosaic are displayed on the opposite (top or
right) side whenever more than one variable is split along a direction.
Set to |
Value
A ggplot2 position scale that can be added to a plot.
Examples
data(titanic)
ggplot(data = titanic, aes(x = product(Class, Sex))) +
geom_mosaic() +
scale_x_productlist("Passenger class / Sex")
Translate shortcut strings to formulas
Description
Translate shortcut strings to formulas
Usage
shortcut_to_formula(shortcut, vars, conds = NULL)
Arguments
shortcut |
Character: "independence", "saturated", or "conditional" |
vars |
Character vector of margin variable names |
conds |
Character vector of conditioning variable names (optional) |
Value
Formula object
Spine partition: divide longest dimension.
Description
Spine partition: divide longest dimension.
Usage
spine(data, bounds, offset = offset, max = NULL)
Arguments
data |
bounds data frame |
bounds |
bounds of space to partition |
offset |
space between spines |
max |
maximum value |
Value
A data frame of rectangle boundaries (l, r, b, t), one row
per level of data.
Examples
data(titanic)
ggplot(data = titanic, aes(x = product(Class))) +
geom_mosaic(divider = "spine")
Internal helper function
Description
Squeeze pieces to lie within specified bounds; directly copied from package productplots
Usage
squeeze(pieces, bounds = bound())
Arguments
pieces |
rectangle specified via l(eft), r(ight), b(ottom), t(op) |
bounds |
rectangle specified via l(eft), r(ight), b(ottom), t(op) |
Value
re-scaled values for piece according to boundaries given by bounds
Author(s)
Hadley Wickham
Theme for mosaic plots
Description
Themes set the general aspect of the plot such as the color of the
background, gridlines, the size and color of fonts.
theme_mosaic provides access to the regular ggplot2 theme, but removes
any background, axes ticks, most of the gridlines, and ensures an aspect
ratio of 1 for better viewing of the mosaics. This theme also applies a bold
face to axes labels and allows for the convenient rotation of category labels.
Usage
theme_mosaic(base_size = 11, base_family = "", rot_labels = 0, ...)
Arguments
base_size |
Base font size. Defaults to 11. |
base_family |
Base font family. Defaults to |
rot_labels |
The angle (in degrees) used to rotate category labels. Defaults to 0 degrees, relative to the current axis orientation. |
... |
Additional arguments passed to |
Details
As with other ggplot2 extensions, themes set the general look-and-feel of the plot such as the color of the background, gridlines, the size and color of fonts. theme_mosaic() provides access to the regular ggplot2 theme, but: removes any background, axes ticks, most of the gridlines, and ensures an aspect ratio of 1 for better viewing of the mosaics. This theme also applies a bold face to axes labels and allows for the convenient rotation of category labels to avoid overlap
Value
A ggplot2 theme object that can be added to a plot.
Author(s)
Gavin Klorfine
Examples
library(ggmosaic2)
data(happy)
ggplot(data = happy,
aes(weight = wtssall, x = product(health), fill = happy)) +
geom_mosaic(na.rm = TRUE) +
theme_mosaic()
Passengers and crew on board the Titanic
Description
A dataset containing some demographics and survival of people on board the Titanic
Usage
titanic
Format
A data frame with 2201 rows and 4 variables:
- Class
factor variable containing the class of a passenger (1st, 2nd, 3rd) or crew.
- Sex
Male/Female.
- Age
Child/Adult. This information is not very reliable, because it was inferred from boarding documents that did not state actual age in years.
- Survived
Yes/No.
Vertical bar partition: height constant, width varies.
Description
Vertical bar partition: height constant, width varies.
Usage
vbar(data, bounds, offset = 0.02, max = NULL)
Arguments
data |
bounds data frame |
bounds |
bounds of space to partition |
offset |
space between spines |
max |
maximum value |
Value
A data frame of rectangle boundaries (l, r, b, t), one row
per level of data.
Examples
data(titanic)
ggplot(data = titanic, aes(x = product(Class))) +
geom_mosaic(divider = "vbar")
Vertical spine partition: width constant, height varies.
Description
Vertical spine partition: width constant, height varies.
Usage
vspine(data, bounds, offset = offset, max = NULL)
Arguments
data |
bounds data frame |
bounds |
bounds of space to partition |
offset |
space between spines |
max |
maximum value |
Value
A data frame of rectangle boundaries (l, r, b, t), one row
per level of data.
Examples
data(titanic)
ggplot(data = titanic, aes(x = product(Class))) +
geom_mosaic(divider = "vspine")