### Run ggalluvial Shiny Example App Source: http://corybrunson.github.io/ggalluvial/articles/shiny.html Execute this code in your R console to launch a ggalluvial example application locally. This is useful if the app does not display directly in the current environment. ```r shiny::shinyAppDir(system.file("examples/ex-shiny-long-data", package="ggalluvial")) ``` -------------------------------- ### Lode Ordering Examples with geom_flow Source: http://corybrunson.github.io/ggalluvial/reference/stat_alluvium.html This example illustrates lode ordering using geom_flow with stat = "alluvium". It shows how to control lode guidance and aesthetic binding. Custom lode ordering can also be applied using the 'order' aesthetic. ```r gg <- ggplot(as.data.frame(Titanic), aes(y = Freq, axis1 = Class, axis2 = Sex, axis3 = Age)) + geom_stratum() + geom_text(stat = "stratum", aes(label = after_stat(stratum))) + scale_x_discrete(limits = c("Class", "Sex", "Age")) # use of lode controls gg + geom_flow(aes(fill = Survived, alpha = Sex), stat = "alluvium", lode.guidance = "forward") #> Warning: Using alpha for a discrete variable is not advised. # prioritize aesthetic binding gg + geom_flow(aes(fill = Survived, alpha = Sex), stat = "alluvium", aes.bind = "alluvia", lode.guidance = "forward") #> Warning: Using alpha for a discrete variable is not advised. # use of custom lode order gg + geom_flow(aes(fill = Survived, alpha = Sex, order = sample(x = 32)), stat = "alluvium") #> Warning: Ignoring unknown aesthetics: order #> Warning: Using alpha for a discrete variable is not advised. ``` -------------------------------- ### Setup ggalluvial and ggplot2 Source: http://corybrunson.github.io/ggalluvial/articles/labels.html Loads the ggalluvial and ggplot2 libraries for plotting. This is a standard setup for using these packages. ```r knitr::opts_chunk$set(fig.width = 6, fig.height = 4, fig.align = "center") library(ggalluvial) ``` -------------------------------- ### Install ggalluvial Development Version from GitHub Source: http://corybrunson.github.io/ggalluvial/index.html Installs the development version of ggalluvial from the main branch on GitHub. Set build_vignettes to TRUE to build vignettes, which requires installing imported packages like alluvial, ggfittext, and ggrepel. ```R remotes::install_github("corybrunson/ggalluvial@main", build_vignettes = TRUE) ``` -------------------------------- ### Install ggalluvial Optimization Branch from GitHub Source: http://corybrunson.github.io/ggalluvial/index.html Installs a development version with experimental functions for reducing alluvial overlaps from the 'optimization' branch on GitHub. Note that this branch may not be up-to-date with the main branch or recent CRAN upgrades. ```R remotes::install_github("corybrunson/ggalluvial", ref = "optimization") ``` -------------------------------- ### Get Help on ggalluvial Conversion Functions Source: http://corybrunson.github.io/ggalluvial/index.html Retrieve detailed documentation for ggalluvial conversion functions, such as to_*_form, using the help() function. ```r help("to_lodes_form") ``` -------------------------------- ### Install ggalluvial from CRAN Source: http://corybrunson.github.io/ggalluvial/index.html Installs the latest stable release of the ggalluvial package from CRAN. ```R install.packages("ggalluvial") ``` -------------------------------- ### Manual Lode Ordering with stat_flow Source: http://corybrunson.github.io/ggalluvial/articles/order-rectangles.html Apply manual ordering to flows within strata using the `order` aesthetic. This example demonstrates how to set a predefined order for lodes at each axis. ```R ggplot(toy, aes(x = collection, stratum = category, alluvium = subject)) + stat_flow(aes(fill = class, order = lode_ord)) + stat_stratum() + stat_flow(geom = "text", aes(fill = class, order = lode_ord, label = subject, hjust = after_stat(flow) == "to")) ``` -------------------------------- ### Get Help on ggalluvial Layers Source: http://corybrunson.github.io/ggalluvial/index.html Use the help() function to get detailed information on specific layers like stat_* or geom_* within the ggalluvial package. ```r help("stat_alluvium") ``` -------------------------------- ### Setup ggalluvial and ggplot2 Source: http://corybrunson.github.io/ggalluvial/articles/order-rectangles.html Sets chunk options for figure dimensions and loads the ggalluvial and ggplot2 libraries. Use this for initializing your R environment for ggalluvial plots. ```r knitr::opts_chunk$set(fig.width = 6, fig.height = 3, fig.align = "center") library(ggalluvial) ``` -------------------------------- ### ggalluvial lode_zigzag function example Source: http://corybrunson.github.io/ggalluvial/articles/order-rectangles.html Demonstrates the output of the lode_zigzag guidance function for different axis configurations. Useful for understanding how 'zigzag' prioritizes adjacent axes. ```r for (i in 1:4) print(lode_zigzag(4, i)) ``` ```text ## [1] 1 2 3 4 ## [1] 2 1 3 4 ## [1] 3 4 2 1 ## [1] 4 3 2 1 ``` -------------------------------- ### Get Help on ggalluvial Datasets Source: http://corybrunson.github.io/ggalluvial/index.html Access documentation for datasets included with the ggalluvial package, like 'vaccinations' and 'majors', using the help() function. ```r help("vaccinations") ``` -------------------------------- ### Setup data function for ggfittext::geom_fit_text Source: http://corybrunson.github.io/ggalluvial/articles/labels.html Displays the setup_data function for ggfittext::geom_fit_text. This function handles the calculation of bounding boxes for fitting text, checking for necessary x/y or xmin/xmax/ymin/ymax aesthetics and optional width/height parameters. ```r print(ggfittext:::GeomFitText$setup_data) ``` -------------------------------- ### Visualize Refugee Volumes by Country and Region Source: http://corybrunson.github.io/ggalluvial/articles/ggalluvial.html This example visualizes refugee volumes by country and region using `geom_alluvium`. It maps country to fill and color, and uses `facet_wrap` to separate by region. ```R data(Refugees, package = "alluvial") country_regions <- c( Afghanistan = "Middle East", Burundi = "Central Africa", `Congo DRC` = "Central Africa", Iraq = "Middle East", Myanmar = "Southeast Asia", Palestine = "Middle East", Somalia = "Horn of Africa", Sudan = "Central Africa", Syria = "Middle East", Vietnam = "Southeast Asia" ) Refugees$region <- country_regions[Refugees$country] ggplot(data = Refugees, aes(x = year, y = refugees, alluvium = country)) + geom_alluvium(aes(fill = country, colour = country), alpha = .75, decreasing = FALSE, outline.type = "upper") + scale_x_continuous(breaks = seq(2003, 2013, 2)) + theme_bw() + theme(axis.text.x = element_text(angle = -30, hjust = 0)) + scale_fill_brewer(type = "qual", palette = "Set3") + scale_color_brewer(type = "qual", palette = "Set3") + facet_wrap(~ region, scales = "fixed") + ggtitle("refugee volume by country and region of origin") ``` -------------------------------- ### Time series alluvia with geom_flow (outline upper) Source: http://corybrunson.github.io/ggalluvial/reference/geom_flow.html Similar to the previous example, but treats 'Year' as an integer and uses outline.type = 'upper' for the flows. ```R # treat 'Year' as a number rather than as a factor wph$Year <- as.integer(as.character(wph$Year)) ggplot(wph, aes(x = Year, alluvium = Region, y = Telephones)) + \ geom_flow(aes(fill = Region, colour = Region), width = 0, outline.type = "upper") ``` -------------------------------- ### ggalluvial lode_backfront function example Source: http://corybrunson.github.io/ggalluvial/articles/order-rectangles.html Illustrates the behavior of the lode_backfront guidance function. This function extends outward in one direction before the other, differing from 'zigzag'. ```r for (i in 1:4) print(lode_backfront(4, i)) ``` ```text ## [1] 1 2 3 4 ## [1] 2 1 3 4 ## [1] 3 2 1 4 ## [1] 4 3 2 1 ``` -------------------------------- ### Illustrate Positioning with stat_stratum and stat_alluvium Source: http://corybrunson.github.io/ggalluvial/reference/stat_alluvium.html This example demonstrates how to use stat_stratum with geom = "errorbar" and stat_alluvium with geom = "pointrange" to visualize data positioning. It also includes geom_line with stat = "alluvium" and geom_text with stat = "stratum" for labeling. ```r ggplot(as.data.frame(Titanic),\ aes(y = Freq,\ axis1 = Class, axis2 = Sex, axis3 = Age,\ color = Survived)) +\ stat_stratum(geom = "errorbar") +\ geom_line(stat = "alluvium") +\ stat_alluvium(geom = "pointrange") +\ geom_text(stat = "stratum", aes(label = after_stat(stratum))) +\ scale_x_discrete(limits = c("Class", "Sex", "Age")) ``` -------------------------------- ### Alluvia and lodes in a plot Source: http://corybrunson.github.io/ggalluvial/reference/geom_lode.html This example shows how to combine geom_alluvium and geom_lode to visualize both the alluvia and the lodes within the same plot. It uses multiple axes for a more detailed representation. ```r gg <- ggplot(as.data.frame(Titanic), aes(y = Freq, axis1 = Class, axis2 = Sex, axis3 = Age, fill = Survived)) # alluvia and lodes gg + geom_alluvium() + geom_lode() ``` -------------------------------- ### ggalluvial lode_backward function example Source: http://corybrunson.github.io/ggalluvial/articles/order-rectangles.html Shows the output of the lode_backward guidance function. This function prioritizes tidiness in the right part of the plot, potentially at the expense of the left. ```r for (i in 1:4) print(lode_backward(4, i)) ``` ```text ## [1] 1 4 3 2 ## [1] 2 4 3 1 ## [1] 3 4 2 1 ## [1] 4 3 2 1 ``` -------------------------------- ### Track Student Curricula Across Semesters Source: http://corybrunson.github.io/ggalluvial/articles/ggalluvial.html This example tracks student curricula changes over semesters using `geom_flow` and `geom_stratum`. It maps curriculum to fill and label, and uses `stat = "alluvium"` to track students. ```R data(majors) majors$curriculum <- as.factor(majors$curriculum) ggplot(majors, aes(x = semester, stratum = curriculum, alluvium = student, fill = curriculum, label = curriculum)) + scale_fill_brewer(type = "qual", palette = "Set2") + geom_flow(stat = "alluvium", lode.guidance = "frontback", color = "darkgray") + geom_stratum() + theme(legend.position = "bottom") + ggtitle("student curricula across several semesters") ``` -------------------------------- ### Create Alluvial Plot from Wide Data (Titanic Example) Source: http://corybrunson.github.io/ggalluvial/index.html Generates an alluvial plot using ggplot2 and ggalluvial from data in wide format. This example visualizes Titanic passenger data, stratifying by Class, Sex, and Age, and filling by Survived status. ```R titanic_wide <- data.frame(Titanic) head(titanic_wide) ggplot(data = titanic_wide, aes(axis1 = Class, axis2 = Sex, axis3 = Age, y = Freq)) + scale_x_discrete(limits = c("Class", "Sex", "Age"), expand = c(.2, .05)) + xlab("Demographic") + geom_alluvium(aes(fill = Survived)) + geom_stratum() + geom_text(stat = "stratum", aes(label = after_stat(stratum))) + theme_minimal() + ggtitle("passengers on the maiden voyage of the Titanic", "stratified by demographics and survival") ``` -------------------------------- ### Full Axis Width Example Source: http://corybrunson.github.io/ggalluvial/reference/geom_stratum.html Demonstrates using geom_stratum with the width set to 1 for full axis width. It also shows how to add labels to the strata using geom_text with stat = "stratum". ```R ggplot(as.data.frame(Titanic), aes(y = Freq, axis1 = Class, axis2 = Sex, axis3 = Age, axis4 = Survived)) + geom_stratum(width = 1) + geom_text(stat = "stratum", aes(label = after_stat(stratum))) + scale_x_discrete(limits = c("Class", "Sex", "Age", "Survived")) ``` -------------------------------- ### Run Shiny App with Wide-Format Data Source: http://corybrunson.github.io/ggalluvial/articles/shiny.html This code launches a Shiny application that visualizes wide-format alluvial data with interactive tooltips. Ensure you have the 'ggalluvial' and 'shiny' packages installed. ```r shiny::shinyAppDir(system.file("examples/ex-shiny-wide-data", package="ggalluvial")) ``` -------------------------------- ### ggalluvial plot with backfront lode guidance Source: http://corybrunson.github.io/ggalluvial/articles/order-rectangles.html Generates a ggalluvial plot using 'backfront' lode guidance. This example visualizes the effect of this guidance on stratum and alluvium ordering. ```r ggplot(toy, aes(x = collection, stratum = category, alluvium = subject)) + stat_alluvium(aes(fill = class), lode.guidance = "backfront") + stat_stratum() + stat_alluvium(geom = "text", aes(label = subject), lode.guidance = "backfront") ``` -------------------------------- ### Order Flows with stat_alluvium Source: http://corybrunson.github.io/ggalluvial/articles/order-rectangles.html Use stat_alluvium to group lodes by class after ordering according to strata. This example shows how to bind aesthetics for flows, which can lead to warnings if aesthetics are not recognized by the geom. ```R ggplot(toy, aes(x = collection, stratum = category, alluvium = subject)) + stat_alluvium(aes(fill = class, label = subject), aes.bind = "flows") + stat_stratum() + stat_alluvium(geom = "text", aes(fill = class, label = subject), aes.bind = "flows") ``` -------------------------------- ### ggalluvial Lode Guidance Function Signatures Source: http://corybrunson.github.io/ggalluvial/reference/lode-guidance-functions.html These functions define the ordering of lodes within strata. They are passed to the `lode.guidance` parameter of `stat_alluvium()` and are invoked with the total number of lodes (n) and a starting index (i). ```R lode_zigzag(n, i) lode_zagzig(n, i) lode_forward(n, i) lode_rightward(n, i) lode_backward(n, i) lode_leftward(n, i) lode_frontback(n, i) lode_rightleft(n, i) lode_backfront(n, i) lode_leftright(n, i) ``` -------------------------------- ### Lodes displayed as strata Source: http://corybrunson.github.io/ggalluvial/reference/geom_lode.html This example illustrates how to use geom_stratum with stat = "alluvium" to display the lodes as strata. This approach emphasizes the boundaries and structure of the alluvial plot. ```r gg + geom_alluvium() + geom_stratum(stat = "alluvium") ``` -------------------------------- ### Faceting with geom_flow and geom_stratum Source: http://corybrunson.github.io/ggalluvial/reference/geom_stratum.html Illustrates the use of facets with geom_flow and geom_stratum. This example visualizes the Titanic dataset, mapping different variables to axes and using faceting by 'Age' to create separate plots for each age group. ```R ggplot(as.data.frame(Titanic), aes(y = Freq, axis1 = Class, axis2 = Sex)) + geom_flow(aes(fill = Survived)) + geom_stratum() + geom_text(stat = "stratum", aes(label = after_stat(stratum))) + scale_x_discrete(limits = c("Class", "Sex")) + facet_wrap(~ Age, scales = "free_y") ``` -------------------------------- ### Create a parallel sets plot of HairEyeColor data Source: http://corybrunson.github.io/ggalluvial/articles/ggalluvial.html Generates a parallel sets plot using the HairEyeColor dataset. This example demonstrates custom color palettes and coordinate flipping for a different visual orientation. ```R ggplot(as.data.frame(HairEyeColor), aes(y = Freq, axis1 = Hair, axis2 = Eye, axis3 = Sex)) + geom_alluvium(aes(fill = Eye), width = 1/8, knot.pos = 0, reverse = FALSE) + scale_fill_manual(values = c(Brown = "#70493D", Hazel = "#E2AC76", Green = "#3F752B", Blue = "#81B0E4")) + guides(fill = "none") + geom_stratum(alpha = .25, width = 1/8, reverse = FALSE) + geom_text(stat = "stratum", aes(label = after_stat(stratum)), reverse = FALSE) + scale_x_continuous(breaks = 1:3, labels = c("Hair", "Eye", "Sex")) + coord_flip() + ggtitle("Eye colors of 592 subjects, by sex and hair color") ``` -------------------------------- ### Plotting lodes with a single axis Source: http://corybrunson.github.io/ggalluvial/reference/geom_lode.html This example demonstrates how to use geom_lode to plot lodes with a single axis, mapping fill and alpha aesthetics for visual distinction. Ensure the data is in a data frame format. ```r ggplot(as.data.frame(Titanic), aes(y = Freq, axis = Class)) + geom_lode(aes(fill = Class, alpha = Survived)) + scale_x_discrete(limits = c("Class")) + scale_alpha_manual(values = c(.25, .75)) ``` -------------------------------- ### lode_zagzig Source: http://corybrunson.github.io/ggalluvial/reference/lode-guidance-functions.html Orders lodes by zigzagging inward from a starting index. ```APIDOC ## lode_zagzig ### Description Orders the numbers 1 through `n`, starting at index `i` and zigzagging outward from `i`, starting in the inward direction. ### Usage ```R lode_zagzig(n, i) ``` ### Arguments * **n** (numeric) - A positive integer. * **i** (numeric) - A positive integer at most `n`. ``` -------------------------------- ### Define Shiny UI with Plot Output and Tooltip Source: http://corybrunson.github.io/ggalluvial/articles/shiny.html Sets up the user interface for a Shiny app, including a plot output that supports hover interactions and an HTML output for displaying tooltips. Use this for creating interactive visualizations. ```r ui <- fluidPage( fluidRow(tags$div( style = "position: relative;", plotOutput("alluvial_plot", height = "650px", hover = hoverOpts(id = "plot_hover") ), htmlOutput("tooltip"))) ) ``` -------------------------------- ### lode_zigzag Source: http://corybrunson.github.io/ggalluvial/reference/lode-guidance-functions.html Orders lodes by zigzagging outward from a starting index. ```APIDOC ## lode_zigzag ### Description Orders the numbers 1 through `n`, starting at index `i` and zigzagging outward from `i`, beginning in the outward direction. ### Usage ```R lode_zigzag(n, i) ``` ### Arguments * **n** (numeric) - A positive integer. * **i** (numeric) - A positive integer at most `n`. ``` -------------------------------- ### Create Alluvial Plot from Long Data (Titanic Example) Source: http://corybrunson.github.io/ggalluvial/index.html Generates an alluvial plot using ggplot2 and ggalluvial from data in long format. This example visualizes Titanic passenger data, mapping Demographic to the x-axis, stratum to the stratum aesthetic, alluvium to the alluvium aesthetic, and Freq to the y-axis. ```R ggplot(data = titanic_long, aes(x = Demographic, stratum = stratum, alluvium = alluvium, y = Freq, label = stratum)) + geom_alluvium(aes(fill = Survived)) + geom_stratum() + geom_text(stat = "stratum") + theme_minimal() + ggtitle("passengers on the maiden voyage of the Titanic", "stratified by demographics and survival") ``` -------------------------------- ### Lode Guidance Functions Source: http://corybrunson.github.io/ggalluvial/reference/index.html Functions to guide the placement and direction of lodes within alluvial plots. ```R lode_zigzag() lode_zagzig() lode_forward() lode_rightward() lode_backward() lode_leftward() lode_frontback() lode_rightleft() lode_backfront() lode_leftright() ``` -------------------------------- ### Convert curriculum data to alluvia format Source: http://corybrunson.github.io/ggalluvial/reference/alluvial-data.html Converts curriculum data to alluvia format using `to_alluvia_form`. Use `is_alluvia_form` for validation, noting potential missing stratum combinations. ```r majors_alluvia <- to_alluvia_form(majors, key = "semester", value = "curriculum", id = "student") is_alluvia_form(majors_alluvia, tidyselect::starts_with("CURR")) ``` -------------------------------- ### data_to_alluvium Helper Function Source: http://corybrunson.github.io/ggalluvial/reference/geom_alluvium.html Prepares data for rendering alluvia by calculating x, y, and shape values for curves. ```r data_to_alluvium( data, knot.prop = TRUE, curve_type = "spline", curve_range = NULL, segments = NULL ) ``` -------------------------------- ### Get Citation for ggalluvial Package Source: http://corybrunson.github.io/ggalluvial/index.html Retrieve the citation information for the ggalluvial package, which should be used when citing the package in publications. ```r citation("ggalluvial") ``` -------------------------------- ### Get Alluvium Information Source: http://corybrunson.github.io/ggalluvial/articles/shiny.html Identifies the last plotted overlapping alluvium polygon under the cursor and extracts its connected node names and width. ```R coord_id <- rev(which(hover_within_flow == 1))[1] flow_label <- paste(groups_to_draw[[coord_id]]$stratum, collapse = ' -> ') flow_n <- groups_to_draw[[coord_id]]$count[1] ``` -------------------------------- ### Get Stratum Label and Count Source: http://corybrunson.github.io/ggalluvial/articles/shiny.html Extracts the stratum's name and count from the plot data using the identified row index. ```R node_label <- pbuilt$data[[2]]$stratum[node_row] node_n <- pbuilt$data[[2]]$count[node_row] ``` -------------------------------- ### Display R session information Source: http://corybrunson.github.io/ggalluvial/articles/labels.html Use `sessioninfo::session_info()` to display detailed information about the R session, including version, OS, and loaded packages. This is useful for reproducibility. ```r sessioninfo::session_info() ``` -------------------------------- ### Warn if color or differentiation aesthetics vary within alluvia Source: http://corybrunson.github.io/ggalluvial/news/index.html The `GeomAlluvium$setup_data()` method now issues a warning if color or differentiation aesthetics vary within individual alluvia, indicating potential issues with visual representation. ```R GeomAlluvium$setup_data(data, ...) # warns if aesthetics vary within alluvia ``` -------------------------------- ### lode_frontback Source: http://corybrunson.github.io/ggalluvial/reference/lode-guidance-functions.html Orders lodes by proceeding forward then backward. ```APIDOC ## lode_frontback ### Description Orders the numbers 1 through `n` by proceeding forward from `i` to `n`, then backward to 1, starting at index `i`. This is an alias for `lode_rightleft`. ### Usage ```R lode_frontback(n, i) ``` ### Arguments * **n** (numeric) - A positive integer. * **i** (numeric) - A positive integer at most `n`. ``` -------------------------------- ### Warning with Lodes Format Data Source: http://corybrunson.github.io/ggalluvial/reference/alluvial-data.html When data is already in lodes format, the `discern` argument is ignored, and a warning is issued. This example demonstrates the behavior and potential data filtering. ```r ggplot(majors[majors$semester %in% paste0("CURR", c(1, 7, 13)), ], aes(x = semester, stratum = curriculum, alluvium = student, label = curriculum)) + geom_alluvium(aes(fill = as.factor(student)), width = 2/5, discern = TRUE) + geom_stratum(width = 2/5, discern = TRUE) + geom_text(stat = "stratum", discern = TRUE) ``` -------------------------------- ### Shiny App Pseudocode Structure Source: http://corybrunson.github.io/ggalluvial/articles/shiny.html Outlines the main steps in a Shiny app for creating an interactive alluvial plot, including data loading, plot generation, coordinate extraction, and tooltip logic. ```r '<(1) Load data.> <(2) Create "ggplot" object for alluvial plot and build it.> <(3) Extract data from built plot object used to create alluvium polygons.> for (polygon in polygons) { '<(4) Use polygon splines to generate coordinates of alluvium boundaries.> } '<(5) Define range of coordinates in grid units and plot units.> for (polygon in polygons) { '<(6) Convert coordinates from grid units to plot units.> } ui <- fluidPage( '<(7) Output plot with hovering enabled.> '<(8) Output tooltip.> ) server <- function(input, output, session) { output$alluvial_plot <- renderPlot({ '<(9) Render the plot.> }) output$tooltip <- renderText({ if ('<(10) mouse cursor is within the plot panel>') { if ('<(11) mouse cursor is within a stratum box>') { '<(11b) Render stratum tooltip.> } else { if ('<(12) mouse cursor is within an alluvium polygon>') { '<(12b) Render alluvium tooltip.> } } } }) } ``` -------------------------------- ### Illustrate Positioning with stat_stratum and geom_line Source: http://corybrunson.github.io/ggalluvial/reference/stat_flow.html Demonstrates positioning using stat_stratum and geom_line with the 'flow' stat. Uses axis aesthetics for data input. ```r ggplot(as.data.frame(Titanic),\ aes(y = Freq,\ axis1 = Class, axis2 = Sex, axis3 = Age,\ color = Survived)) +\ stat_stratum(geom = "errorbar") +\ geom_line(stat = "flow") +\ stat_flow(geom = "pointrange") +\ geom_text(stat = "stratum", aes(label = after_stat(stratum))) +\ scale_x_discrete(limits = c("Class", "Sex", "Age")) ``` -------------------------------- ### Discontiguous Alluvium with Missing Values Source: http://corybrunson.github.io/ggalluvial/reference/stat_alluvium.html Illustrates a discontiguous alluvium plot using babynames data. This example shows how to handle missing values by expanding the data and filling with zeros. ```R data(babynames, package = "babynames") bn <- subset(babynames, prop >= .01 & sex == "F" & year > 1962 & year < 1968) ggplot(data = bn, aes(x = year, alluvium = name, y = prop)) + geom_alluvium(aes(fill = name, color = name == "Tammy"), decreasing = TRUE, show.legend = FALSE) + scale_color_manual(values = c("#00000000", "#000000")) ``` ```R bn2 <- merge(bn, expand.grid(year = unique(bn$year), name = unique(bn$name)), all = TRUE) ggplot(data = bn2, aes(x = year, alluvium = name, y = prop)) + geom_alluvium(aes(fill = name, color = name == "Tammy"), decreasing = TRUE, show.legend = FALSE) + scale_color_manual(values = c("#00000000", "#000000")) ``` ```R bn2$prop[is.na(bn2$prop)] <- 0 ggplot(data = bn2, aes(x = year, alluvium = name, y = prop)) + geom_alluvium(aes(fill = name, color = name == "Tammy"), decreasing = TRUE, show.legend = FALSE) + scale_color_manual(values = c("#00000000", "#000000")) ``` -------------------------------- ### Alluvial Diagram with Proportional Knot Positioning Source: http://corybrunson.github.io/ggalluvial/reference/geom_alluvium.html Illustrates an alluvial diagram with irregular spacing between axes for a continuous variable. This example uses proportional knot positioning, which is the default behavior. ```r # irregular spacing between axes of a continuous variable refugees_sub <- subset(alluvial::Refugees, year %in% c(2003, 2005, 2010, 2013)) gg <- ggplot(data = refugees_sub, aes(x = year, y = refugees, alluvium = country)) + theme_bw() + scale_fill_brewer(type = "qual", palette = "Set3") # proportional knot positioning (default) gg + geom_alluvium(aes(fill = country), alpha = .75, decreasing = FALSE, width = 1/2) + geom_stratum(aes(stratum = country), decreasing = FALSE, width = 1/2) ``` -------------------------------- ### Cemented Alluvial Diagram with Default Distillation Source: http://corybrunson.github.io/ggalluvial/reference/stat_alluvium.html Creates a cemented alluvial diagram using default distillation, which selects the first most common alluvium. `cement.alluvia = TRUE` is applied to both geom_flow and geom_text. ```R gg + geom_flow(stat = "alluvium", color = "black", cement.alluvia = TRUE) + geom_text(aes(label = after_stat(lode)), stat = "alluvium", cement.alluvia = TRUE) ``` -------------------------------- ### Rename is_alluvial_* and to_* functions Source: http://corybrunson.github.io/ggalluvial/news/index.html Functions for testing and converting alluvial formats are renamed for consistency with tidyverse conventions. Old names are deprecated. For example, `is_alluvial_alluvia` is renamed to `is_alluvia_form`. ```R is_alluvia_form(data, key, value, id) ``` ```R to_lodes_form(data, key, value, id) ``` -------------------------------- ### Custom Lode Guidance Function Source: http://corybrunson.github.io/ggalluvial/reference/stat_alluvium.html Demonstrates using a custom lode.guidance function with geom_flow for alluvial diagrams. Ensure the custom function correctly handles the expected input and output. ```R lode_custom <- function(n, i) { stopifnot(n == 3) switch( i, `1` = 1:3, `2` = c(2, 3, 1), `3` = 3:1 ) } gg + geom_flow(aes(fill = Survived, alpha = Sex), stat = "alluvium", aes.bind = "flow", lode.guidance = lode_custom) ``` -------------------------------- ### Load vaccinations dataset Source: http://corybrunson.github.io/ggalluvial/reference/vaccinations.html This code snippet shows how to access the 'vaccinations' dataset. No specific imports are required if the package is already loaded. ```r vaccinations ``` -------------------------------- ### lode_backfront Source: http://corybrunson.github.io/ggalluvial/reference/lode-guidance-functions.html Orders lodes by proceeding backward then forward. ```APIDOC ## lode_backfront ### Description Orders the numbers 1 through `n` by proceeding backward from `i` to 1, then forward to `n`, starting at index `i`. This is an alias for `lode_leftright`. ### Usage ```R lode_backfront(n, i) ``` ### Arguments * **n** (numeric) - A positive integer. * **i** (numeric) - A positive integer at most `n`. ``` -------------------------------- ### geom_flow with facets and quintic flows Source: http://corybrunson.github.io/ggalluvial/reference/geom_flow.html Illustrates using geom_flow with facets and the 'quintic' curve type for flows. Includes aesthetic mapping for fill and width control. ```R ggplot(as.data.frame(Titanic), \ aes(y = Freq, \ axis1 = Class, axis2 = Sex)) + \ geom_flow(aes(fill = Age), width = .4, curve_type = "quintic") + \ geom_stratum(width = .4) + \ geom_text(stat = "stratum", aes(label = after_stat(stratum)), size = 3) + \ scale_x_discrete(limits = c("Class", "Sex")) + \ facet_wrap(~ Survived, scales = "fixed") ``` -------------------------------- ### Visualize Vaccination Survey Responses Source: http://corybrunson.github.io/ggalluvial/articles/ggalluvial.html This example visualizes vaccination survey responses over time using `geom_flow` and `geom_stratum`. It maps response to fill and label, and uses `y = freq` to represent cohort size. ```R data(vaccinations) vaccinations <- transform(vaccinations, response = factor(response, rev(levels(response)))) ggplot(vaccinations, aes(x = survey, stratum = response, alluvium = subject, y = freq, fill = response, label = response)) + scale_x_discrete(expand = c(.1, .1)) + geom_flow() + geom_stratum(alpha = .5) + geom_text(stat = "stratum", size = 3) + theme(legend.position = "none") + ggtitle("vaccination survey responses at three points in time") ``` -------------------------------- ### Add distill parameter to to_alluvia() Source: http://corybrunson.github.io/ggalluvial/news/index.html The `to_alluvia()` function now has a `distill` parameter to control the inclusion of original variables that vary within `id` values. This is based on a distilling function that returns a single value from a vector. ```R to_alluvia(data, id = id, distill = mean) ``` -------------------------------- ### Basic geom_flow with strata and labels Source: http://corybrunson.github.io/ggalluvial/reference/geom_flow.html Demonstrates the use of geom_flow with geom_stratum and geom_text for displaying strata labels. Requires ggplot2 and ggalluvial. ```R ggplot(as.data.frame(Titanic), \ aes(y = Freq, \ axis1 = Class, axis2 = Sex, axis3 = Age)) + \ geom_flow() + \ scale_x_discrete(limits = c("Class", "Sex", "Age")) + \ geom_stratum() + \ geom_text(stat = "stratum", aes(label = after_stat(stratum))) + \ ggtitle("Alluvial plot of Titanic passenger demographic data") ``` -------------------------------- ### Create Toy Data for ggalluvial Source: http://corybrunson.github.io/ggalluvial/articles/order-rectangles.html Generates a small, complex data frame named 'toy' for demonstrating ggalluvial functionality. It includes subject, collection, category, and class variables. ```r # toy data set set.seed(0) toy <- data.frame( subject = rep(LETTERS[1:5], times = 4), collection = rep(1:4, each = 5), category = rep( sample(c("X", "Y"), 16, replace = TRUE), rep(c(1, 2, 1, 1), times = 4) ), class = c("one", "one", "one", "two", "two") ) print(toy) ``` -------------------------------- ### Basic ggalluvial plot with text labels Source: http://corybrunson.github.io/ggalluvial/articles/labels.html Creates a ggalluvial plot of vaccination survey responses, attempting to label strata using geom_text. This example illustrates the problem of labels not fitting within small strata. ```r ggplot(vaccinations, aes(x = survey, stratum = response, alluvium = subject, y = freq, fill = response, label = response)) + scale_x_discrete(expand = c(.1, 0)) + geom_flow(width = 1/4) + geom_stratum(alpha = .5, width = 1/4) + geom_text(stat = "stratum", size = 4) + theme(legend.position = "none") + ggtitle("vaccination survey responses", "labeled using `geom_text()`") ``` -------------------------------- ### lode_rightleft Source: http://corybrunson.github.io/ggalluvial/reference/lode-guidance-functions.html Orders lodes by proceeding forward then backward. ```APIDOC ## lode_rightleft ### Description Orders the numbers 1 through `n` by proceeding forward from `i` to `n`, then backward to 1, starting at index `i`. This is an alias for `lode_frontback`. ### Usage ```R lode_rightleft(n, i) ``` ### Arguments * **n** (numeric) - A positive integer. * **i** (numeric) - A positive integer at most `n`. ``` -------------------------------- ### Render Alluvium Tooltip Source: http://corybrunson.github.io/ggalluvial/articles/shiny.html Renders an HTML tooltip for an alluvium, displaying connected node names and width, positioned using CSS coordinates from the hover event. ```R renderTags( tags$div( flow_label, tags$br(), "n =", flow_n, style = paste0( "position: absolute; ", "top: ", hover$coords_css$y + offset, "px; ", "left: ", hover$coords_css$x + offset, "px; ", "background: gray; ", "padding: 3px; ", "color: white; " ) ) )$html ``` -------------------------------- ### Manual Lode Ordering with stat_alluvium Source: http://corybrunson.github.io/ggalluvial/articles/order-rectangles.html Manually order lodes at each axis by passing a data column to the `order` aesthetic. This ensures cases are ordered according to their IDs within their respective strata. ```R lode_ord <- rep(seq(5), times = 4) ggplot(toy, aes(x = collection, stratum = category, alluvium = subject)) + stat_alluvium(aes(fill = class, order = lode_ord)) + stat_stratum() + stat_alluvium(geom = "text", aes(fill = class, order = lode_ord, label = subject)) ``` -------------------------------- ### Printing StatStratum$compute_panel Source: http://corybrunson.github.io/ggalluvial/articles/labels.html This snippet shows how to print the `compute_panel` method of the `StatStratum` object in R, which is part of the ggalluvial package. ```r print(StatStratum$compute_panel) ``` -------------------------------- ### Restrict GeomFlow$draw_panel() to complete.cases() Source: http://corybrunson.github.io/ggalluvial/news/index.html The `GeomFlow$draw_panel()` method now restricts calculations to `complete.cases()`, ensuring that only flows with both starting and terminating axes are considered. This differs from `StatFlow$compute_panel()`, which would exclude missing aesthetic values from legends. ```R GeomFlow$draw_panel(data, ...) # internally restricts to complete.cases(data) ``` -------------------------------- ### lode_leftright Source: http://corybrunson.github.io/ggalluvial/reference/lode-guidance-functions.html Orders lodes by proceeding backward then forward. ```APIDOC ## lode_leftright ### Description Orders the numbers 1 through `n` by proceeding backward from `i` to 1, then forward to `n`, starting at index `i`. This is an alias for `lode_backfront`. ### Usage ```R lode_leftright(n, i) ``` ### Arguments * **n** (numeric) - A positive integer. * **i** (numeric) - A positive integer at most `n`. ```