Skip to contents

Generate a simple two-column alluvial (Sankey-style) plot with Gradient styling using ggalluvial.

Usage

g6tr_two_stage_alluvial_plot(
  data,
  id,
  left_var,
  right_var,
  weight_var = NULL,
  na.rm = TRUE,
  color_scale = NULL,
  text_size = 4,
  text_color = "#FFFFFF"
)

Arguments

data

A tibble containing at least two categorical and ID columns.

id

ID column.

left_var

Character. Name of the “from” column.

right_var

Character. Name of the “to” column.

weight_var

Character. (Optional) Name of numeric weight column; if NULL, equal weights assumed.

na.rm

Logical; remove NA values when computing proportions (default TRUE).

color_scale

Optional named character vector mapping factor levels to colours.

text_size

Base font size for all labels.

text_color

Text colour. (default "#FFFFFF").

Examples

library(dplyr)
library(ggplot2)

# sample data
old_segments <- state.name[1:5]
new_segments <- state.name[25:28]
sample_size <- 200
data <- tibble(
  id = paste0("r_", seq_len(sample_size)),
  old_segment = sample(old_segments, sample_size, TRUE),
  new_segment = sample(new_segments, sample_size, TRUE),
  weight = runif(sample_size)
)

## You can set the order in whcih levels are arranged in the plot
## by updating the levels in the factor column
set.seed(2324)
data$old_segment <- factor(data$old_segment, levels = sample(old_segments, 5))
levels(data$old_segment)
#> [1] "Alabama"    "California" "Arkansas"   "Alaska"     "Arizona"   

# create alluvial plot
p <- g6tr_two_stage_alluvial_plot(
  data,
  id = "id",
  left_var = "old_segment",
  right_var = "new_segment",
  weight_var = "weight"
)
#> ! `new_segment` was converted to a factor.
#> ℹ Plot order will follow data order: "Nebraska", "Missouri", "Nevada", and
#>   "Montana"
#> → To control order, set factor levels on `new_segment` before calling this
#>   function.
p


## Change x axis labels
x_labels <- c("old_segment" = "Old Segment", "new_segment" = "New Segment")
p + scale_x_discrete(labels = x_labels, expand = c(.1, 0))
#> Scale for x is already present.
#> Adding another scale for x, which will replace the existing scale.


## Include colour scale
all_segments <- c(state.name[c(1:5, 25:28)])
color_scale <- sample(colors(distinct = TRUE), length(all_segments))
names(color_scale) <- all_segments

data |>
  g6tr_two_stage_alluvial_plot(
    id = "id",
    left_var = "old_segment",
    right_var = "new_segment",
    weight_var = "weight",
    color_scale = color_scale
  )
#> ! `new_segment` was converted to a factor.
#> ℹ Plot order will follow data order: "Nebraska", "Missouri", "Nevada", and
#>   "Montana"
#> → To control order, set factor levels on `new_segment` before calling this
#>   function.