ggplot2绘制冲积条形图

作者: R语言数据分析指南 | 来源:发表于2020-11-23 22:59 被阅读0次

    常见的堆砌条形图看腻了,试试冲积条形吧!!

    rm(list=ls())
    pacman::p_load(tidyverse,magrittr,reshape,RColorBrewer,ggalluvial)
    
    computed_persent <- function(path) {
      data <- path %>%
        read.delim(check.names = FALSE, row.names = 1)
      data2 <- data %>%
        mutate(sum = rowSums(.), persent = sum / sum(sum) * 100, sum = NULL,) %>%
        rbind(filter(., persent < 1) %>% colSums()) %>%
        mutate(OTU_ID = c(data %>% rownames(), "others"))
      filter(data2[1:(nrow(data2) - 1),], persent > 1) %>%
        rbind(data2[nrow(data2),]) %>%
        set_rownames(seq_len(nrow(.))) %>%
        return()
    }
    path <- "genus.xls" #此处写入的是文件路径
    a1 <- computed_persent(path) %>% melt() %>% filter(variable !="persent")
    
    colors <-c("#E41A1C","#1E90FF","#FF8C00","#4DAF4A","#984EA3",
               "#40E0D0","#FFC0CB","#00BFFF","#FFDEAD","#90EE90",
               "#EE82EE","#00FFFF","#F0A3FF", "#0075DC", 
               "#993F00","#4C005C","#2BCE48","#FFCC99",
               "#808080","#94FFB5","#8F7C00","#9DCC00",
               "#C20088","#003380","#FFA405","#FFA8BB",
               "#426600","#FF0010","#5EF1F2","#00998F",
               "#740AFF","#990000","#FFFF00")
    
    a2 <- "group.txt" %>% read.delim()
    a4 <- NULL
    
    for (i in seq_len(nrow(a1))) { 
      a4[i] <- a2[which(a2[, 1] == a1[i, 2]), 2] }
    
    a1[, 4] <- a4
    #以上部分为数据过滤步骤
    head(a1)
    #------------------------------------------------------------------------------------
                          OTU_ID variable value V4
    1                  Aeromonas       B1   144  B
    2                Bacteroides       B1   282  B
    3 Barnesiellaceae_uncultured       B1    34  B
    4             Bradyrhizobium       B1   928  B
    5              Brevundimonas       B1   414  B
    6              Cetobacterium       B1   550  B
    #----------------------------------------------------------------------------------
    ggplot(a1,aes(variable,value,alluvium=OTU_ID,stratum = OTU_ID))+
      geom_alluvium(aes(fill = OTU_ID),alpha = .5,width = 0.6) + 
      geom_stratum(aes(fill = OTU_ID),width = 0.6)+
      facet_grid(. ~V4,scales = "free",space="free_x")+
      labs(x="",y="Proportions")+
      scale_fill_manual(values = colors)+labs(fill="")+
      theme(legend.title=element_blank())+
      scale_y_continuous(expand=c(0,0))+
      theme(panel.background = element_rect(fill='white',
                                      colour='black'))
    
    bar.png
    参考:http://corybrunson.github.io/ggalluvial/articles/ggalluvial.html
    数据链接:https://pan.baidu.com/s/1HDVjd47YWN5_ayJCElGIpg
    提取码: ejrr

    相关文章

      网友评论

        本文标题:ggplot2绘制冲积条形图

        本文链接:https://www.haomeiwen.com/subject/qyuviktx.html