plot_counts_2D: Plot counts of observations across two dimensions, optionally...

View source: R/export-ObservationCounts.R

plot_counts_2DR Documentation

Plot counts of observations across two dimensions, optionally stratified

Description

Computes the number of observations for each combination of two specified variables, and displays the result as a heatmap using ggplot2. If a stratification variable is provided, counts are calculated per strata and strata-specific heatmaps are displayed in individual panels. If an additional stratification variable is provided, separate plot windows are created for each level.

Usage

plot_counts_2D(
  data,
  x,
  y,
  stratify_by = NULL,
  for_each = NULL,
  color_gradient = c("blue", "beige", "red"),
  title = "Observation counts",
  legend_title = NULL,
  subtitle = NULL,
  x_lab = NULL,
  y_lab = NULL
)

Arguments

data

Data frame containing all input variables.

x

Variable in data whose values define the x-axis for counts.

y

Variable in data whose values define the y-axis for counts.

stratify_by

(Optional) Stratification variable. If supplied, counts are computed for each combination of x, y and stratify_by, and separate heatmaps are generated per level of stratify_by.

for_each

(Optional) Additional stratification variable. If supplied, separate plot windows are created per level of for_each.

color_gradient

(Optional) Color gradient for the heatmap. Specified as a character vector of three colors, representing: c(<low_counts>, <middle_counts>, <high_counts>). Defaults to c("blue", "beige", "red"). Colors must be recognized by ggplot.

title

(Optional) Plot title; defaults to "Observation counts".

legend_title

(Optional) Legend title for color gradient; defaults to "Count".

subtitle

(Optional) Plot subtitle; defaults to NULL if for for_each is NULL, defaults to <name of for_each>: <level of for_each> for each plot window if for_each is supplied.

x_lab

(Optional) Label for the x-axis; defaults to the name of x.

y_lab

(Optional) Label for the y-axis; defaults to the name of y.

Value

If for_each is not supplied, a ggplot object showing a heatmap of counts for each x-y combination, optionally faceted by stratify_by. If for_each is supplied, a named list of such ggplot objects, one per unique value of for_each.

See Also

plot_counts_1D, plot_binned_counts, plot_counts_with_mean, ggplot

Examples

data("toy_data")
# Heatmap of counts by age and period
plot_counts_2D(toy_data, x = age, y = period)
# Heatmap of counts by age and period, stratified by education
plot_counts_2D(toy_data, x = period, y = age,
               stratify_by = education)
# Heatmap of counts by age and period, stratified by education, for each sex
plot_counts_2D(toy_data, x = period, y = age,
               stratify_by = education, for_each = sex)

MAPCtools documentation built on June 25, 2025, 5:09 p.m.