'Problem creating alluvial diagram using ggalluvial
I have this dataset:
type <- c(1, 2, NA, 1, 2, NA)
freq <- c(75, 12, 25, 69, 22, 32)
time <- c("before", "before", "before", "after", "after", "after")
df <- data.frame(type , freq, time )
I need to make a graph like this (with different data obviously):
I tried to follow the guide here: https://cran.r-project.org/web/packages/ggalluvial/vignettes/ggalluvial.html
Using this code:
ggplot(modechoice,
aes(x = time, stratum = type, alluvium = time,
y = freq,
fill = type, label = type)) +
scale_x_discrete(expand = c(.1, .1)) +
geom_flow() +
geom_stratum(alpha = .5) +
geom_text(stat = "stratum", size = 3) +
theme(legend.position = "none") +
ggtitle("x")
But I get the error that my data is not recognised as an alluvial. What am I doing wrong?
Solution 1:[1]
You should have a fourth variable which is linked with your time variable, that's why I created an extra variable as an example. You can use the following code:
type <- c("1", "2", "NA", "1", "2", "NA")
freq <- c(75, 12, 25, 69, 22, 32)
time1 <- c("before", "before", "before", "after", "after", "after")
time2 <- c("after", "before", "after", "after", "before", "after")
df <- data.frame(type , freq, time1, time2)
library(tidyverse)
library(ggalluvial)
ggplot(df,
aes(y = freq, axis1 = time1, axis2 = time2)) +
geom_alluvium(aes(fill = type), width = 1/12) +
geom_stratum(width = 1/12, fill = "black", color = "grey") +
geom_label(stat = "stratum", aes(label = after_stat(stratum))) +
scale_x_discrete(limits = c("time1", "time2"), expand = c(.05, .05)) +
scale_fill_brewer(type = "qual", palette = "Set1") +
ggtitle("x")
Output:
Edit after Victor Nielson comment:
type <- c("1", "2", "NA", "1", "2", "NA")
freq <- c(75, 12, 25, 69, 22, 32)
time1 <- c("before", "before", "before", "before", "before", "before")
time2 <- c("after", "after", "after", "after", "after", "after")
df <- data.frame(type , freq, time1, time2)
library(tidyverse)
library(ggalluvial)
ggplot(df,
aes(y = freq, axis1 = time1, axis2 = time2)) +
geom_alluvium(aes(fill = type), width = 1/12) +
geom_stratum(width = 1/12, fill = "black", color = "grey") +
geom_label(stat = "stratum", aes(label = after_stat(stratum))) +
scale_x_discrete(limits = c("time1", "time2"), expand = c(.05, .05)) +
scale_fill_brewer(type = "qual", palette = "Set1") +
ggtitle("x")
Output:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |



