I am trying to make an alluvial plot for changes in species composition. Lets say, that some species occurs on sites currently. but under slimate change, some species will remain, some will disapear and novel species will come.
I would like to show this transition using alluvial plot. But, I can't properly claim it to be properly plot? Here is my working example:
library(ggalluvial)
# try a simple test: still not working, needs further simlification !
df_test <- data.frame(site = c(1,1,1,2,2,1,2,2,2,2),
site_ch = c("a","a","a","b","b","a","b","b","b","b"),
acc = c("piab",
"abies",
"fasy",
"piab",
"fasy",
"frax",
"piab",
"fasy",
"frax",
"abies"
),
scenario = rep(c("current", 'rcp25'), each = 5)) %>%
mutate(acc = factor(acc),
site_ch = factor(site_ch),
scenario = factor(scenario))
# Ensure each species appears across both scenarios per site
df_alluvial <- df_test %>%
count(site, scenario, acc) %>% # Count occurrences of each species per site per scenario
complete(site, scenario, acc, fill = list(n = 0)) %>% # Ensure all combinations exist
rename(freq = n) %>% # Rename count column for clarity
arrange(site, acc, scenario) #%>%
#dplyr::filter(freq !=0)
# Ensure scenario is a factor in correct order
df_alluvial <- df_alluvial %>%
mutate(scenario = factor(scenario, levels = c("current", "rcp25")),
acc = factor(acc),
site = factor(site)) %>%
group_by(scenario, acc) %>%
dplyr::summarise(sum_n = sum(freq, na.rm = T))
# Create an alluvial plot
ggplot(df_alluvial,
aes(x = scenario, stratum = acc, alluvium = sum_n, y = sum_n, fill = acc)) +
geom_alluvium(alpha = 0.6, aes(fill = acc)) + # Connects species across scenarios
geom_stratum() + # Adds category blocks
theme_minimal() +
labs(title = "Species Presence Across Scenarios",
x = "Scenario",
y = "Frequency",
fill = "Species") +
scale_fill_brewer(palette = "Set2")
I get an error:
Error in `geom_alluvium()`:
! Problem while computing stat.
ℹ Error occurred in the 1st layer.
Caused by error in `setup_data()`:
! Data is not in a recognized alluvial form (see `help('alluvial-data')` for details).
Run `rlang::last_trace()` to see where the error occurred.
This is how my output should look like (a bit more elegant of course! ):
In your final ggplot, in the aes()
, alluvium = acc
replace alluvium = sum_n
;
Use geom_flow()
instead of geom_alluvium()
ggplot(df_alluvial,
aes(x = scenario,
y = sum_n,
stratum = acc,
alluvium = acc)) +
geom_flow() +
geom_stratum() +
theme_minimal() +
labs(title = "Species Presence Across Scenarios",
x = "Scenario",
y = "Frequency",
fill = "Species") +
scale_fill_brewer(palette = "Set2")