今天从别人的博客中,了解到如何更好地画桑基图,特记录下该代码。 更多知识分享请到 https://zouhua.top/。
加载R包
library(dplyr)
library(tibble)
library(ggplot2)
library(ggalluvial)
导入数据
otu <- read.delim('otu_table.txt', sep = '\t', stringsAsFactors = FALSE, check.names = FALSE)
otu$OTU <- factor(otu$OTU, levels = unique(otu$OTU))
tax <- read.delim('taxonomy.txt', sep = '\t', stringsAsFactors = FALSE, check.names = FALSE)
tax$Phylum <- factor(tax$Phylum, levels = unique(tax$Phylum))
group <- read.delim('group.txt', sep = '\t', stringsAsFactors = FALSE, check.names = FALSE)
group$Sample <- factor(group$Sample, levels = unique(group$Sample))
合并 OTU 丰度、OTU 门水平分类、样本分组
otu1 <- reshape::melt(otu, id = 'OTU')
otu2 <- merge(otu1, tax, by = 'OTU')
names(otu2)[2] <- 'Sample'
otu3 <- merge(otu2, group, by = 'Sample')
整理成 ggplot2 作图格式,以便于 ggalluvial 绘制冲击图
otu4 <- reshape::melt(otu3, id = 'value')
names(otu4) <- c('value', 'type', 'detail')
type <- summary(otu4$type)
otu4$flow <- rep(1:type[1], length(type))
预指定 OTU、门分类、样本、分组的颜色
color_otu <- c('#8DD3C7', '#FFFFB3', '#BEBADA', '#FB8072', '#80B1D3', '#FDB462',
'#B3DE69', '#FCCDE5', '#BC80BD', '#CCEBC5', '#FFED6F', '#E41A1C', '#377EB8',
'#4DAF4A', '#984EA3', '#FF7F00', '#FFFF33', '#A65628', '#F781BF', '#66C2A5')
color_sample <- c('#6181BD', '#F34800', '#64A10E', '#FF00FF', '#c7475b', '#049a0b')
color_phylum <- c('#BEAED4', '#FDC086', '#FFFF99', '#386CB0', '#F0027F')
color_group <- c('#4253ff', '#ff4308')
冲击图
p <- ggplot(otu4, aes(x = type, y = value,
stratum = detail, alluvium = flow, fill = detail)) +
geom_stratum() +
geom_text(stat = 'stratum', infer.label = TRUE, size = 2.5) +
geom_flow() +
scale_fill_manual(values = c(color_sample, color_otu, color_phylum, color_group)) +
scale_x_discrete(limits = c('Phylum', 'OTU', 'Sample', 'Group')) +
scale_y_continuous(expand = c(0, 0)) +
labs(x = '', y = 'Abundance') +
theme(legend.position = 'none', axis.line = element_line(),
panel.background = element_blank())
p
# 输出图片至本地
ggsave('test.pdf', p, width = 10, height = 5)
参考
参考文章如引起任何侵权问题,可以与我联系,谢谢。
网友评论