mosaic | R Documentation |
The mosaic()
function generates imbalance plots for
contingency tables with up to three variables. Frequencies in the
contingency table are represented as tiles (rectangles), with each tile's
size proportional to the frequency of the corresponding group within the
entire dataset. The x-axis scale remains fixed across mosaic plots,
enabling straightforward comparisons of imbalance across treatment groups.
mosaic(
data = NULL,
y = NULL,
group = NULL,
facet = NULL,
ncol = 1,
group_counts = FALSE,
group_counts_size = 4,
significance = FALSE,
plot_name = NULL,
overwrite = FALSE,
...
)
data |
A non-empty |
y |
A single string or unquoted symbol representing the name of a
numeric column in the |
group |
A single string or unquoted symbol representing the name of a
factor or character column in |
facet |
A single string or unquoted symbol representing the name of a
variable in |
ncol |
A single integer. The value should be less than or equal to the
number of unique categories in the |
group_counts |
A logical flag. If |
group_counts_size |
A single numeric value that specifies the size of
the group count labels in millimeters ('mm'). This value is passed to the
|
significance |
A logical flag; defaults to |
plot_name |
A string specifying a valid file name or path for the plot.
If set to |
overwrite |
A logical flag (default |
... |
Additional arguments to pass to |
A ggplot
object representing the contingency table of y
and
group
as a mosaic plot, optionally grouped by facet
if specified.
## Example: Creating a Mosaic Plot of the Titanic Dataset
## This plot visualizes survival rates by gender across different passenger
## classes. By setting `significance = TRUE`, you can highlight statistically
## significant differences within each rectangle of the mosaic plot.
library(ggplot2)
# Load Titanic dataset and convert to data frame
titanic_df <- as.data.frame(Titanic)
# Expand the dataset by repeating rows according to 'Freq'
titanic_long <- titanic_df[rep(
seq_len(nrow(titanic_df)),
titanic_df$Freq
), ]
# Remove the 'Freq' column as it is no longer needed
titanic_long$Freq <- NULL
# Plot the data using mosaic() and modify the result using additional ggplot2
# functions
p <- vecmatch::mosaic(
data = titanic_long,
y = Survived,
group = Sex,
facet = Class,
ncol = 2,
significance = TRUE
)
p <- p +
theme_minimal()
p
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.