Last active
February 13, 2020 17:37
-
-
Save romanhaa/83d3edc90e8ee465604f5c59d0289775 to your computer and use it in GitHub Desktop.
Making an alluvial plot in R with ggalluvial
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library("tidyverse") | |
library("ggalluvial") | |
# original data | |
# every genomic bin of 200bp is assigned one of 8 possible chromatin states | |
# note that group1-3 are factors | |
input_data | |
# A tibble: 855,156 x 4 | |
# bin group1 group2 group3 | |
# <chr> <fct> <fct> <fct> | |
# 1 chrX:0-200 8 8 8 | |
# 2 chrX:200-400 8 8 8 | |
# 3 chrX:400-600 8 8 8 | |
# 4 chrX:600-800 8 8 8 | |
# 5 chrX:800-1000 8 8 8 | |
# 6 chrX:1000-1200 8 8 8 | |
# 7 chrX:1200-1400 8 8 8 | |
# 8 chrX:1400-1600 8 8 8 | |
# 9 chrX:1600-1800 8 8 8 | |
# 10 chrX:1800-2000 8 8 8 | |
# … with 855,146 more rows | |
# group counts by experimental groups | |
input_data_grouped <- input_data %>% | |
group_by(group1, group2, group3) %>% | |
tally() | |
# A tibble: 265 x 4 | |
# Groups: group1, group2 [58] | |
# group1 group2 group3 n | |
# <fct> <fct> <fct> <int> | |
# 1 1 1 1 703 | |
# 2 1 1 2 21 | |
# 3 1 1 3 14 | |
# 4 1 1 4 175 | |
# 5 1 1 5 4 | |
# 6 1 1 6 1 | |
# 7 1 1 8 14 | |
# 8 1 2 1 12 | |
# 9 1 2 2 2 | |
# 10 1 2 3 4 | |
# … with 255 more rows | |
# transform data into alluvial shape using the `to_lodes_form()` function | |
transition_lodes <- to_lodes_form(input_data_grouped, key = "test", axes = 1:3) | |
# A tibble: 795 x 4 | |
# n alluvium test stratum | |
# <int> <int> <fct> <fct> | |
# 1 703 1 group1 1 | |
# 2 21 2 group1 1 | |
# 3 14 3 group1 1 | |
# 4 175 4 group1 1 | |
# 5 4 5 group1 1 | |
# 6 1 6 group1 1 | |
# 7 14 7 group1 1 | |
# 8 12 8 group1 1 | |
# 9 2 9 group1 1 | |
# 10 4 10 group1 1 | |
# … with 785 more rows | |
# plot | |
p <- ggplot( | |
transition_lodes, | |
aes( | |
x = test, | |
stratum = stratum, | |
alluvium = alluvium, | |
y = n | |
) | |
) + | |
geom_alluvium(aes(fill = stratum)) + | |
geom_stratum(aes(fill = stratum)) + | |
geom_label(stat = "stratum") + | |
theme_bw() + | |
labs(x = "", y = "") + | |
theme_bw() + | |
theme( | |
legend.position = "none", | |
axis.title = element_blank(), | |
axis.text.x = element_text(face = "bold", colour = "black", size=15), | |
axis.text.y = element_blank(), | |
axis.ticks.y = element_blank(), | |
panel.grid.major = element_blank(), | |
panel.grid.minor = element_blank(), | |
panel.border = element_blank(), | |
axis.ticks.x = element_blank() | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The code above will result in this plot:
Even though it gives me a warning. I might have to revise this code in the future.