| Title: | 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. |
| Authors: | Michael Friendly [aut, cre, cph] (ORCID: <https://orcid.org/0000-0002-3237-0941>), Gavin Klorfine [aut] (ORCID: <https://orcid.org/0009-0003-0395-4512>), Haley Jeppson [aut] (ORCID: <https://orcid.org/0000-0003-2524-4063>), Heike Hofmann [aut] (ORCID: <https://orcid.org/0000-0001-6216-5183>), Di Cook [aut] (ORCID: <https://orcid.org/0000-0002-3813-7155>), Hadley Wickham [ctb] (ORCID: <https://orcid.org/0000-0003-4757-117X>) |
| Maintainer: | Michael Friendly <[email protected]> |
| License: | GPL (>= 2) |
| Version: | 0.5.1 |
| Built: | 2026-09-27 22:39:28 UTC |
| Source: | https://github.com/friendly/ggmosaic2 |
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.
ddecker(direction = "h")ddecker(direction = "h")
direction |
direction of first split |
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.
data(titanic) ggplot(data = titanic, aes(x = product(Class, Sex))) + geom_mosaic(divider = ddecker("v"))data(titanic) ggplot(data = titanic, aes(x = product(Class, Sex))) + geom_mosaic(divider = ddecker("v"))
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.
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" )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" )
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 |
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.
A Facet object that can be added to a ggplot.
Gavin Klorfine
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))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))
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.
flyfly
A data frame with 1040 rows and 27 variables:
Respondent ID
How often do you travel by plane?
Do you ever recline your seat when you fly?
How tall are you?
Do you have any children under 18?
n a row of three seats, who should get to use the two arm rests?
In a row of two seats, who should get to use the middle arm rest?
Who should have control over the window shade?
Is it rude to move to an unsold seat on a plane?
Generally speaking, is it rude to say more than a few words to the stranger sitting next to you on a plane?
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?
Under normal circumstances, does a person who reclines their seat during a flight have any obligation to the person sitting behind them?
Is it rude to recline your seat on a plane?
Given the opportunity, would you eliminate the possibility of reclining seats on planes entirely?
Is it rude to ask someone to switch seats with you in order to be closer to friends?
Is it rude to ask someone to switch seats with you in order to be closer to family?
Is it rude to wake a passenger up if you are trying to go to the bathroom?
Is it rude to wake a passenger up if you are trying to walk around?
In general, is it rude to bring a baby on a plane?
In general, is it rude to knowingly bring unruly children on a plane?
Have you ever used personal electronics during take off or landing in violation of a flight attendant's direction?
Have you ever smoked a cigarette in an airplane bathroom when it was against the rules?
Gender
Age
Household Income
Education
Region
https://github.com/fivethirtyeight/data/tree/master/flying-etiquette-survey
A mosaic plot is a convenient graphical summary of the conditional distributions in a contingency table and is composed of spines in alternating directions.
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, ... )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, ... )
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
|
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.
A ggplot2 layer that can be added to a plot.
location of center of the rectangle
location of center of the rectangle
location of bottom left corner
location of bottom right corner
location of top left corner
location of top right corner
Gavin Klorfine
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 donttestdata(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
A mosaic plat with jittered dots
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, ... )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, ... )
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
|
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.
A ggplot2 layer that can be added to a plot.
location of bottom left corner
location of bottom right corner
location of top left corner
location of top right corner
Gavin Klorfine
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"))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"))
A mosaic plot with text or labels
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, ... )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, ... )
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 |
A ggplot2 layer that can be added to a plot.
Gavin Klorfine
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)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)
Geom proto
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
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
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.
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:
data(happy)data(happy)
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.
hbar(data, bounds, offset = 0.02, max = NULL)hbar(data, bounds, offset = 0.02, max = NULL)
data |
bounds data frame |
bounds |
bounds of space to partition |
offset |
space between spines |
max |
maximum value |
A data frame of rectangle boundaries (l, r, b, t), one row
per level of data.
data(titanic) ggplot(data = titanic, aes(x = product(Class))) + geom_mosaic(divider = "hbar")data(titanic) ggplot(data = titanic, aes(x = product(Class))) + geom_mosaic(divider = "hbar")
Horizontal spine partition: height constant, width varies.
hspine(data, bounds, offset = offset, max = NULL)hspine(data, bounds, offset = offset, max = NULL)
data |
bounds data frame |
bounds |
bounds of space to partition |
offset |
space between spines |
max |
maximum value |
A data frame of rectangle boundaries (l, r, b, t), one row
per level of data.
data(titanic) ggplot(data = titanic, aes(x = product(Class))) + geom_mosaic(divider = "hspine")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.
mosaic(direction = "h")mosaic(direction = "h")
direction |
direction of first split |
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.
data(titanic) ggplot(data = titanic, aes(x = product(Class, Sex))) + geom_mosaic(divider = mosaic("v"))data(titanic) ggplot(data = titanic, aes(x = product(Class, Sex))) + geom_mosaic(divider = mosaic("v"))
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.
mosaic_settings(divider, offset, expected)mosaic_settings(divider, offset, expected)
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 |
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.
An object of class "ggmosaic_settings" that can be added to a
ggplot with +.
Gavin Klorfine
geom_mosaic(), stat_mosaic(), geom_mosaic_text(),
stat_mosaic_text(), geom_mosaic_jitter(), stat_mosaic_jitter(),
mosaic(), and ddecker()
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)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)
Wrapper for a list
product(...)product(...)
... |
Unquoted variables going into the product plot. |
A list of expressions (see rlang::exprs()), one per argument,
used inside aes() to mark the variables that define the mosaic's
product formula.
data(titanic) ggplot(data = titanic, aes(x = product(Survived, Class), fill = Survived)) + geom_mosaic()data(titanic) ggplot(data = titanic, aes(x = product(Survived, Class), fill = Survived)) + geom_mosaic()
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.
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" )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 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 |
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").
A ggplot2 fill scale that can be added to a plot.
Gavin Klorfine
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))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))
Used internally to determine class of variable x
## S3 method for class 'productlist' scale_type(x)## S3 method for class 'productlist' scale_type(x)
x |
variable |
character string "productlist"
Determining scales for mosaics
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() ) ScaleContinuousProductscale_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
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 |
A ggplot2 position scale that can be added to a plot.
data(titanic) ggplot(data = titanic, aes(x = product(Class, Sex))) + geom_mosaic() + scale_x_productlist("Passenger class / Sex")data(titanic) ggplot(data = titanic, aes(x = product(Class, Sex))) + geom_mosaic() + scale_x_productlist("Passenger class / Sex")
Spine partition: divide longest dimension.
spine(data, bounds, offset = offset, max = NULL)spine(data, bounds, offset = offset, max = NULL)
data |
bounds data frame |
bounds |
bounds of space to partition |
offset |
space between spines |
max |
maximum value |
A data frame of rectangle boundaries (l, r, b, t), one row
per level of data.
data(titanic) ggplot(data = titanic, aes(x = product(Class))) + geom_mosaic(divider = "spine")data(titanic) ggplot(data = titanic, aes(x = product(Class))) + geom_mosaic(divider = "spine")
Squeeze pieces to lie within specified bounds; directly copied from package productplots
squeeze(pieces, bounds = bound())squeeze(pieces, bounds = bound())
pieces |
rectangle specified via l(eft), r(ight), b(ottom), t(op) |
bounds |
rectangle specified via l(eft), r(ight), b(ottom), t(op) |
re-scaled values for piece according to boundaries given by bounds
Hadley Wickham
Geom proto
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
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
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.
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.
theme_mosaic(base_size = 11, base_family = "", rot_labels = 0, ...)theme_mosaic(base_size = 11, base_family = "", rot_labels = 0, ...)
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 |
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
A ggplot2 theme object that can be added to a plot.
Gavin Klorfine
library(ggmosaic2) data(happy) ggplot(data = happy, aes(weight = wtssall, x = product(health), fill = happy)) + geom_mosaic(na.rm = TRUE) + theme_mosaic()library(ggmosaic2) data(happy) ggplot(data = happy, aes(weight = wtssall, x = product(health), fill = happy)) + geom_mosaic(na.rm = TRUE) + theme_mosaic()
A dataset containing some demographics and survival of people on board the Titanic
titanictitanic
A data frame with 2201 rows and 4 variables:
factor variable containing the class of a passenger (1st, 2nd, 3rd) or crew.
Male/Female.
Child/Adult. This information is not very reliable, because it was inferred from boarding documents that did not state actual age in years.
Yes/No.
Vertical bar partition: height constant, width varies.
vbar(data, bounds, offset = 0.02, max = NULL)vbar(data, bounds, offset = 0.02, max = NULL)
data |
bounds data frame |
bounds |
bounds of space to partition |
offset |
space between spines |
max |
maximum value |
A data frame of rectangle boundaries (l, r, b, t), one row
per level of data.
data(titanic) ggplot(data = titanic, aes(x = product(Class))) + geom_mosaic(divider = "vbar")data(titanic) ggplot(data = titanic, aes(x = product(Class))) + geom_mosaic(divider = "vbar")
Vertical spine partition: width constant, height varies.
vspine(data, bounds, offset = offset, max = NULL)vspine(data, bounds, offset = offset, max = NULL)
data |
bounds data frame |
bounds |
bounds of space to partition |
offset |
space between spines |
max |
maximum value |
A data frame of rectangle boundaries (l, r, b, t), one row
per level of data.
data(titanic) ggplot(data = titanic, aes(x = product(Class))) + geom_mosaic(divider = "vspine")data(titanic) ggplot(data = titanic, aes(x = product(Class))) + geom_mosaic(divider = "vspine")