Alluvial Diagrams in ggplot2

Jason Cory Brunson

2018-07-06

The ggalluvial package strives to adapt the style and flexibility of the alluvial package to the principles and frameworks of the tidyverse. This vignette

Many other resources exist for visualizing categorical data in R, including several more basic plot types that are likely to more accurately convey proportions to viewers when the data are not so structured as to warrant an alluvial diagram. In particular, check out Michael Friendly’s vcd and vcdExtra packages (PDF) for a variety of statistically-motivated categorical data visualization techniques, Hadley Wickham’s productplots package and Haley Jeppson and Heike Hofmann’s descendant ggmosaic package for product or mosaic plots, and Nicholas Hamilton’s ggtern package for ternary coordinates. Other related packages are mentioned below.

Alluvial diagrams

Here’s a quintessential alluvial diagram:

The next section details how the elements of this image encode information about the underlying dataset. For now, we use the image as a point of reference to define the following elements of a typical alluvial diagram:

As the examples in the next section will demonstrate, which of these elements are incorporated into an alluvial diagram depends on both how the underlying data is structured and what the creator wants the diagram to communicate.

Alluvial data

ggalluvial recognizes two formats of “alluvial data”, treated in detail in the following subsections, but which basically correspond to the “wide” and “long” formats of categorical repeated measures data. A third, tabular (or array), form is popular for storing data with multiple categorical dimensions, such as the Titanic and UCBAdmissions datasets.1 For consistency with tidy data principles and ggplot2 conventions, ggalluvial does not accept tabular input; base::data.frame() converts such an array to an acceptable data frame.

Alluvia (wide) format

The wide format reflects the visual arrangement of an alluvial diagram, but “untwisted”: Each row corresponds to a cohort of observations that take a specific value at each variable, and each variable has its own column. An additional column contains the weight of each row, e.g. the number of observational units in the cohort, which may be used to control the heights of the strata.2 Basically, the wide format consists of one row per alluvium. This is the format into which the base function as.data.frame() transforms a frequency table, for instance the 3-dimensional UCBAdmissions dataset:

head(as.data.frame(UCBAdmissions), n = 12)
##       Admit Gender Dept Freq
## 1  Admitted   Male    A  512
## 2  Rejected   Male    A  313
## 3  Admitted Female    A   89
## 4  Rejected Female    A   19
## 5  Admitted   Male    B  353
## 6  Rejected   Male    B  207
## 7  Admitted Female    B   17
## 8  Rejected Female    B    8
## 9  Admitted   Male    C  120
## 10 Rejected   Male    C  205
## 11 Admitted Female    C  202
## 12 Rejected Female    C  391
is_alluvia_form(as.data.frame(UCBAdmissions), axes = 1:3, silent = TRUE)
## [1] TRUE

This format is inherited from the first version of ggalluvial, which modeled it after usage in alluvial: The user declares any number of axis variables, which stat_alluvium() and stat_stratum() recognize and process in a consistent way:

ggplot(as.data.frame(UCBAdmissions),
       aes(y = Freq, axis1 = Gender, axis2 = Dept)) +
  geom_alluvium(aes(fill = Admit), width = 1/12) +
  geom_stratum(width = 1/12, fill = "black", color = "grey") +
  geom_label(stat = "stratum", label.strata = TRUE) +
  scale_x_discrete(limits = c("Gender", "Dept"), expand = c(.05, .05)) +
  scale_fill_brewer(type = "qual", palette = "Set1") +
  ggtitle("UC Berkeley admissions and rejections, by sex and department")

An important feature of these diagrams is the meaningfulness of the vertical axis: No gaps are inserted between the strata, so the total height of the diagram reflects the cumulative weight of the observations. The diagrams produced by ggalluvial conform (somewhat; keep reading) to the “grammar of graphics” principles of ggplot2, and this prevents users from producing “free-floating” diagrams like the Sankey diagrams showcased here.3 ggalluvial parameters and existing ggplot2 functionality can also produce parallel sets plots, illustrated here using the Titanic dataset:4

ggplot(as.data.frame(Titanic),
       aes(y = Freq,
           axis1 = Survived, axis2 = Sex, axis3 = Class)) +
  geom_alluvium(aes(fill = Class),
                width = 0, knot.pos = 0, reverse = FALSE) +
  guides(fill = FALSE) +
  geom_stratum(width = 1/8, reverse = FALSE) +
  geom_text(stat = "stratum", label.strata = TRUE, reverse = FALSE) +
  scale_x_continuous(breaks = 1:3, labels = c("Survived", "Sex", "Class")) +
  coord_flip() +
  ggtitle("Titanic survival by class and sex")

This format and functionality are useful for many applications and will be retained in future versions. They also involve some conspicuous deviations from ggplot2 norms:

Furthermore, format aesthetics like fill are necessarily fixed for each alluvium; they cannot, for example, change from axis to axis according to the value taken at each. This means that, although they can reproduce the branching-tree structure of parallel sets, this format and functionality cannot produce alluvial diagrams with the color schemes featured here (“Alluvial diagram”) and here (“Controlling colors”), which are “reset” at each axis.

Lodes (long) format

The long format recognized by ggalluvial contains one row per lode, and can be understood as the result of “gathering” (in the dplyr sense) or “pivoting” (in the Microsoft Excel sense) the axis columns of a dataset in the alluvia format into a key-value pair of columns encoding the axis as the key and the stratum as the value. This format requires an additional indexing column that links the rows corresponding to a common cohort, i.e. the lodes of a single alluvium:

UCB_lodes <- to_lodes_form(as.data.frame(UCBAdmissions),
                           axes = 1:3,
                           id = "Cohort")
head(UCB_lodes, n = 12)
##    Freq Cohort     x  stratum
## 1   512      1 Admit Admitted
## 2   313      2 Admit Rejected
## 3    89      3 Admit Admitted
## 4    19      4 Admit Rejected
## 5   353      5 Admit Admitted
## 6   207      6 Admit Rejected
## 7    17      7 Admit Admitted
## 8     8      8 Admit Rejected
## 9   120      9 Admit Admitted
## 10  205     10 Admit Rejected
## 11  202     11 Admit Admitted
## 12  391     12 Admit Rejected
is_lodes_form(UCB_lodes, key = x, value = stratum, id = Cohort, silent = TRUE)
## [1] TRUE

The functions that convert data between wide (alluvia) and long (lodes) format include several parameters that help preserve ancillary information. See help("alluvial-data") for examples.

The same stat and geom can receive data in this format using a different set of positional aesthetics, also specific to ggalluvial:

Heights can vary from axis to axis, allowing users to produce bump charts like those showcased here.5 In these cases, the strata contain no more information than the alluvia and often not plotted. For convenience, both stat_alluvium() and stat_flow() will accept arguments for x and alluvium even if none is given for stratum.6 As an example, we can group countries in the Refugees dataset by region, in order to compare refugee volumes at different scales:

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) +
  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")
## Warning in f(...): Some differentiation aesthetics vary within alluvia, and will be diffused by their first value.
## Consider using `geom_flow()` instead.

The format allows us to assign aesthetics that change from axis to axis along the same alluvium, which is useful for repeated measures datasets. This requires generating a separate graphical object for each flow, as implemented in geom_flow(). The plot below uses a set of (changes to) students’ academic curricula over the course of several semesters. Since geom_flow() calls stat_flow() by default (see the next example), we override it with stat_alluvium() in order to track each student across all semesters:

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 = "rightleft",
            color = "darkgray") +
  geom_stratum() +
  theme(legend.position = "bottom") +
  ggtitle("student curricula across several semesters")

The stratum heights y are unspecified, so each row is given unit height. This example demonstrates one way ggalluvial handles missing data. The alternative is to set the parameter na.rm to TRUE.7 Missing data handling (specifically, the order of the strata) also depends on whether the stratum variable is character or factor/numeric.

Finally, lode format gives us the option to aggregate the flows between adjacent axes, which may be appropriate when the transitions between adjacent axes are of primary importance. We can demonstrate this option on data from the influenza vaccination surveys conducted by the RAND American Life Panel:

data(vaccinations)
levels(vaccinations$response) <- rev(levels(vaccinations$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")

This diagram ignores any continuity between the flows between axes. This “memoryless” plot produces a less cluttered diagram, in which at most one flow proceeds from each stratum at one axis to each stratum at the next, but at the cost of being able to track each cohort across the entire diagram.

Appendix

devtools::session_info()
## Session info -------------------------------------------------------------
##  setting  value                       
##  version  R version 3.3.2 (2016-10-31)
##  system   x86_64, darwin13.4.0        
##  ui       X11                         
##  language (EN)                        
##  collate  en_US.UTF-8                 
##  tz       America/New_York            
##  date     2018-07-06
## Packages -----------------------------------------------------------------
##  package      * version    date       source                             
##  assertthat     0.2.0      2017-04-11 cran (@0.2.0)                      
##  backports      1.1.2      2017-12-13 CRAN (R 3.3.2)                     
##  base         * 3.3.2      2016-10-31 local                              
##  bindr          0.1.1      2018-03-13 CRAN (R 3.3.2)                     
##  bindrcpp     * 0.2.2      2018-03-29 CRAN (R 3.3.2)                     
##  brew           1.0-6      2011-04-13 CRAN (R 3.3.0)                     
##  callr          2.0.4      2018-05-15 CRAN (R 3.3.2)                     
##  cli            1.0.0      2017-11-23 Github (r-lib/cli@ab1c3aa)         
##  colorspace     1.3-2      2016-12-14 CRAN (R 3.3.2)                     
##  commonmark     1.5        2018-04-28 CRAN (R 3.3.2)                     
##  crayon         1.3.4      2017-09-16 cran (@1.3.4)                      
##  curl           3.2        2018-03-28 CRAN (R 3.3.2)                     
##  datasets     * 3.3.2      2016-10-31 local                              
##  debugme        1.1.0      2017-10-22 cran (@1.1.0)                      
##  desc           1.2.0      2018-05-01 CRAN (R 3.3.2)                     
##  devtools     * 1.13.5     2018-02-18 CRAN (R 3.3.2)                     
##  digest         0.6.15     2018-01-28 CRAN (R 3.3.2)                     
##  dplyr          0.7.5      2018-05-19 CRAN (R 3.3.2)                     
##  evaluate       0.10.1     2017-06-24 cran (@0.10.1)                     
##  fs             1.2.3      2018-06-08 CRAN (R 3.3.2)                     
##  ggalluvial   * 0.9.0      <NA>       local                              
##  ggfittext      0.6.0      2018-07-06 CRAN (R 3.3.2)                     
##  ggplot2      * 3.0.0      2018-07-03 CRAN (R 3.3.2)                     
##  ggrepel        0.8.0      2018-05-09 CRAN (R 3.3.2)                     
##  git2r          0.21.0     2018-01-04 CRAN (R 3.3.2)                     
##  glue           1.2.0      2017-10-29 CRAN (R 3.3.2)                     
##  graphics     * 3.3.2      2016-10-31 local                              
##  grDevices    * 3.3.2      2016-10-31 local                              
##  grid           3.3.2      2016-10-31 local                              
##  gtable         0.2.0      2016-02-26 CRAN (R 3.3.0)                     
##  htmltools      0.3.6      2017-04-28 cran (@0.3.6)                      
##  httr           1.3.1      2017-08-20 cran (@1.3.1)                      
##  knitr          1.20       2018-02-20 CRAN (R 3.3.2)                     
##  labeling       0.3        2014-08-23 CRAN (R 3.3.0)                     
##  lazyeval       0.2.1      2017-10-29 cran (@0.2.1)                      
##  magrittr       1.5        2014-11-22 CRAN (R 3.3.0)                     
##  MASS           7.3-50     2018-04-30 CRAN (R 3.3.2)                     
##  memoise        1.1.0      2017-04-21 cran (@1.1.0)                      
##  methods      * 3.3.2      2016-10-31 local                              
##  munsell        0.5.0      2018-06-12 CRAN (R 3.3.2)                     
##  pillar         1.2.3      2018-05-25 CRAN (R 3.3.2)                     
##  pkgconfig      2.0.1      2017-03-21 CRAN (R 3.3.2)                     
##  pkgdown      * 1.1.0      2018-06-02 CRAN (R 3.3.2)                     
##  plyr           1.8.4      2016-06-08 CRAN (R 3.3.0)                     
##  processx       3.1.0      2018-05-15 CRAN (R 3.3.2)                     
##  purrr          0.2.5      2018-05-29 CRAN (R 3.3.2)                     
##  R6             2.2.2      2017-06-17 cran (@2.2.2)                      
##  RColorBrewer   1.1-2      2014-12-07 CRAN (R 3.3.0)                     
##  Rcpp           0.12.17    2018-05-18 CRAN (R 3.3.2)                     
##  rematch        1.0.1      2016-04-21 cran (@1.0.1)                      
##  rlang          0.2.1      2018-05-30 CRAN (R 3.3.2)                     
##  rmarkdown      1.10       2018-06-11 CRAN (R 3.3.2)                     
##  roxygen2       6.0.1      2017-02-06 CRAN (R 3.3.2)                     
##  rprojroot      1.3-2      2018-01-03 CRAN (R 3.3.2)                     
##  rstudioapi     0.7.0-9000 2018-02-05 Github (rstudio/rstudioapi@109e593)
##  scales         0.5.0      2017-08-24 CRAN (R 3.3.2)                     
##  stats        * 3.3.2      2016-10-31 local                              
##  stringi        1.2.3      2018-06-12 CRAN (R 3.3.2)                     
##  stringr        1.3.1      2018-05-10 CRAN (R 3.3.2)                     
##  testthat       2.0.0      2017-12-13 CRAN (R 3.3.2)                     
##  tibble         1.4.2      2018-01-22 CRAN (R 3.3.2)                     
##  tidyr          0.8.1      2018-05-18 CRAN (R 3.3.2)                     
##  tidyselect     0.2.4      2018-02-26 CRAN (R 3.3.2)                     
##  tools          3.3.2      2016-10-31 local                              
##  utils        * 3.3.2      2016-10-31 local                              
##  whisker        0.3-2      2013-04-28 CRAN (R 3.3.0)                     
##  withr          2.1.2      2018-06-23 Github (jimhester/withr@dbcd7cd)   
##  xml2           1.1.1      2017-01-24 CRAN (R 3.3.2)                     
##  yaml           2.1.19     2018-05-01 CRAN (R 3.3.2)

  1. See Friendly’s tutorial, linked above, for a discussion.

  2. Previously, weights were passed to the weight aesthetic rather than to y. This prevented scale_y_continuous() from correctly transforming scales, and anyway it was inconsistent with the behavior of geom_bar().

  3. The ggforce package includes parallel set geom and stat layers to produce similar diagrams that can be allowed to free-float.

  4. A greater variety of parallel sets plots are implemented in the ggparallel package.

  5. If bumping is unnecessary, consider using geom_area() instead.

  6. stat_stratum() will similarly accept arguments for x and stratum without alluvium. If both strata and either alluvia or flows are to be plotted, though, all three parameters need arguments.

  7. Be sure to set na.rm consistently in each layer, in this case both the flows and the strata.