R语言实战:使用ggplot2绘制微生物组物种丰度堆叠柱状图 | 您所在的位置:网站首页 › r语言plot画柱状图代码 › R语言实战:使用ggplot2绘制微生物组物种丰度堆叠柱状图 |
数据和代码获取:请查看主页个人信息
在本篇文章中,我们将使用R语言来实现一个微生物组物种丰度堆叠柱状图。下面是一步步的过程,以及与之对应的代码:首先,我们需要导入在本示例中使用到的R包。这里我们使用了tidyverse,reshape2,phyloseq和ggsci。 Step 1: 导入所需的包 rm(list=ls()) pacman::p_load(tidyverse,reshape2,phyloseq,ggsci)接下来,我们从phyloseq包中导入OTU表,并将OTU表与分类信息表合并为一个数据框。 Step 2: 读取数据 otufile % summarise_if(is.numeric, sum, na.rm = TRUE) %>% t() %>% as.data.frame() %>% set_names('SUM') %>% arrange(desc(SUM)) %>% rownames_to_column('OTU') %>% head(9) top在此步骤中,我们从整个OTU表中筛选出表达量前9的OTU,并保存它们的信息。 Step 4: 整理数据 otu_top % rownames_to_column('OTU') %>% filter(OTU %in% top$OTU) %>% column_to_rownames('OTU') %>% t() %>% as.data.frame() %>% rownames_to_column('sample') otu_top # 除了前9个表达量较高的OTU之外,其他被OTU定义为“Others” otu_others % rownames_to_column('OTU') %>% filter(! OTU %in% rownames(top)) %>% summarise_if(is.numeric, sum, na.rm = TRUE) %>% t() %>% as.data.frame() %>% set_names('Others') %>% rownames_to_column('sample') head(otu_others) # 接下来这步比较关键,在分类变量数据中加入Others。 tax_top % filter(OTU %in% top$OTU) %>% column_to_rownames('OTU') %>% t() %>% as.data.frame() %>% mutate(Others = 'Others') %>% t() %>% as.data.frame() %>% rownames_to_column('OTU') tax_topStep 5: 合并数据 # 绘图数据合并 dat % left_join(otu_others) %>% melt(id.vars = 'sample') %>% set_names(c('sample', 'OTU', 'value')) %>% left_join(tax_top) head(dat) Step 6: 绘制OTU物种丰度堆叠柱状图 ggplot(dat, aes(sample, value, fill = OTU)) + geom_bar(stat="identity", position = 'fill')+ xlab("") + ylab("") + theme_classic(base_size = 7) + scale_y_continuous(expand = c(0,0)) + ggtitle('OTU') + guides(fill=guide_legend(title=NULL)) + theme(axis.text.x=element_text(angle=45,vjust=1, hjust=1), legend.key.size = unit(10, "pt")) + ggsci::scale_fill_npg() 为了方便后续绘制不同分类级别的物种丰度堆叠柱状图,我们定义一个通用绘图函数pic()。 Step 7: 定义绘图函数 pic |
CopyRight 2018-2019 实验室设备网 版权所有 |