Learn R Programming

scf (version 1.0.5)

scf_plot_bbar: Stacked Bar Chart of Two Discrete Variables in SCF Data

Description

Visualizes a discrete-discrete bivariate distribution using stacked bars based on pooled cross-tabulations from scf_xtab(). Use this function to visualize the relationship between two discrete variables.

Usage

scf_plot_bbar(
  design,
  rowvar,
  colvar,
  scale = c("percent", "count"),
  percent_by = c("total", "row", "col"),
  title = NULL,
  xlab = NULL,
  ylab = NULL,
  fill_colors = NULL,
  row_labels = NULL,
  col_labels = NULL
)

Value

A ggplot2 object.

Arguments

design

A scf_mi_survey object created by scf_load(). Must contain five implicates with replicate weights.

rowvar

A one-sided formula for the x-axis grouping variable (e.g., ~edcl).

colvar

A one-sided formula for the stacked fill variable (e.g., ~racecl).

scale

Character. One of "percent" (default) or "count".

percent_by

Character. One of "total" (default), "row", or "col" — determines normalization base when scale = "percent".

title

Optional character string for the plot title.

xlab

Optional character string for the x-axis label.

ylab

Optional character string for the y-axis label.

fill_colors

Optional vector of fill colors to pass to ggplot2::scale_fill_manual().

row_labels

Optional named vector to relabel row categories (x-axis).

col_labels

Optional named vector to relabel col categories (legend).

Implementation

This function calls scf_xtab() to estimate the joint distribution of two categorical variables across multiply-imputed SCF data. The result is translated into a ggplot2 stacked bar chart using pooled counts or normalized percentages.

Examples

Run this code
# Do not implement these lines in real analysis:
# Use functions `scf_download()` and `scf_load()`
td <- tempfile("plot_bbar_")
dir.create(td)

src <- system.file("extdata", "scf2022_mock_raw.rds", package = "scf")
file.copy(src, file.path(td, "scf2022.rds"), overwrite = TRUE)
scf2022 <- scf_load(2022, data_directory = td)

# Example for real analysis: Stacked bar chart: education by ownership
scf_plot_bbar(scf2022, ~own, ~edcl)

# Example for real analysis: Column percentages instead of total percent
scf_plot_bbar(scf2022, ~own, ~edcl, percent_by = "col")

# Example for real analysis: Raw counts (estimated number of households)
scf_plot_bbar(scf2022, ~own, ~edcl, scale = "count")

# Do not implement these lines in real analysis: Cleanup for package check
unlink(td, recursive = TRUE, force = TRUE)

Run the code above in your browser using DataLab