Skip to content

How to: Alluvial Chart with rcrunch

Gordon Shotwell edited this page May 30, 2018 · 2 revisions

Someone recently asked us to create an "alluvial" chart from a Crunch dataset. First I googled alluvial chart, then I created the script below. Please feel free to borrow from this to suit your own needs.

library(ggalluvial) # thanks R community!\
library(crunch)  
library(dplyr)  
login()  

ds <- loadDataset("some dataset")  
df <- as.data.frame(ds[, c('R5', 'R6', 'disposition', 'gender')], force=TRUE)  
df <- filter(df, disposition == 'Complete')  
tmp <- as.data.frame(table(df$R5, df$R6, df$gender))  
names(tmp) <- c('Past', 'Current', 'Gender', 'Freq')  

is_alluvial(tmp, logical = FALSE, silent = TRUE)  

ggplot(tmp,  
  aes(weight = Freq, axis1 = Past, axis2 = Current)) +  
  geom_alluvium(aes(fill = Gender), width = 1/12) +  
  geom_stratum(width = 1/12, fill = "black", color = "grey") +  
  geom_label(stat = "stratum", label.strata = TRUE) +  
  scale_x_continuous(breaks = 1:2, labels = c("Past", "Current")) +  
  scale_fill_brewer(type = "qual", palette = "Set1") +  
  ggtitle("Past to Current Location, Urbanity Preference by Gender")
Clone this wiki locally