今天從別人的博客中栏笆,了解到如何更好地畫闪鲋迹基圖,特記錄下該代碼竖伯。
加載R包
library(dplyr)
library(tibble)
library(ggplot2)
library(ggalluvial)
導入數(shù)據(jù)
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)