Alluvial plot 冲积图绘制

2024-09-19 17:42:26 浏览数 (3)

Alluvial plot 冲积图绘制

Alluvial plot(冲积图)是一种流程图,最初设计用于展示网络结构随时间的变化。这种图表特别适用于展示数据中的分类如何从一个组别流向另一个组别,例如在分析不同子类型样本中的细胞如何在不同聚类中分布,或者在不同数据集中的细胞如何在不同聚类中分布的情况

Alluvial plot 通过水平或垂直的流带(ribbons)来表示数据流,这些流带的宽度可以表示数据量或者数据的比例。在R语言中,可以通过ggalluvial包来创建这种图表。

今天在工作中需要绘制这么一张冲积图:

将表格形式改成冲积图形式,即菌-代谢产物-基因的联系,其中

这张表格展示了不同的肠道菌群(乳杆菌属、埃希氏菌属、梭菌属等)及其相关菌种,并列出了与这些菌群相关的基因或代谢标志物(已经隐藏,用a,b,c...等替代)。如:

  1. 乳杆菌属 (Lactobacillus)
  2. 菌种 列出了三个乳杆菌属的菌种:
  • Lactobacillus ruminis
  • Lactobacillus plantarum
  • Lactobacillus paracasei
  • 相关基因或代谢物
  • a,b,c,d,e

代码

代码语言:r复制
rm(list=ls())
library(ggplot2)
#install.packages("ggalluvial")
library(ggalluvial)
library(dplyr)
library(tidyr)



data <- data.frame(
  Genus = c(
    "Lactobacillus", "Lactobacillus", "Lactobacillus", 
    "Escherichia", 
    "Clostridium", "Clostridium", "Clostridium",
    "Blautia",
    "Oscillospira",
    "Akkermansia"
  ),
  Species = c(
    "Lactobacillus ruminis", "Lactobacillus plantarum", "Lactobacillus paracasei",
    NA, 
    "Clostridium sporogenes LII.LtrB-eryR", "Clostridium sporogenes ATCC 15579", "Clostridium scindens VPI 12708",
    NA,
    NA ,
    NA
  ),
  Marker = c(
    "a,b,c,d,e", "a,b,c,d,e", "a,b,c,d,e",
    "a, c", 
    "a,b,d", "a,b,d", "a,b,d",
    "c", 
    "e",
    "c,f"
  ),
  value = 1  # 流量大小
)

# 拆分 Marker 列
data_long <- data %>%
  mutate(Marker = strsplit(as.character(Marker), ", ")) %>% unnest(Marker)

ggplot(data_long,
       aes(axis1 = Genus, axis2 = Species, axis3 = Marker, y = value))  
  geom_alluvium(aes(fill = Genus), width = 0.1)  
  geom_stratum(width = 0.1, fill = "gray")  
  geom_text(stat = "stratum", aes(label = after_stat(stratum)), size = 3)  
  scale_x_discrete(limits = c("Genus", "Species", "Marker"), expand = c(0.15, 0.05))  
  scale_fill_brewer(type = "qual", palette = "Set2")  
  ggtitle("Alluvium Plot for Gut Microbiota and Markers")  
  theme_minimal()  
  theme(axis.text.y = element_blank(),
        axis.ticks.y = element_blank())

# 绘制 Alluvium Plot

ggplot(data_long,
       aes(axis1 = Genus, axis2 = Species, axis3 = Marker, y = value))  
  geom_alluvium(aes(fill = Genus), width = 0.3)    # 确保流动线根据 Genus 着色
  geom_stratum(aes(fill = Genus), width = 0.3)    # 层次块根据 Genus 着色
  geom_text(stat = "stratum", aes(label = after_stat(stratum)), size = 3)    # 添加标签
  scale_x_discrete(limits = c("Genus", "Species", "Marker"), expand = c(0.15, 0.05))  
  scale_fill_brewer(type = "qual", palette = "Set2")    # 选择调色板
  ggtitle("Alluvium Plot for Gut Microbiota and Markers")  
  theme_minimal()  
  theme(plot.title = element_text(hjust = 0.5),#设置标题居中
        axis.text.y = element_blank(),
        axis.ticks.y = element_blank(),
        panel.grid = element_blank(),
        panel.background = element_rect(fill = "white", color = NA),  # 设置面板背景为纯白
        plot.background = element_rect(fill = "white", color = NA))
ggsave("alluviumPlot1.tiff",height = 7,width = 8)

0 人点赞