R语言如何绘制桑基气泡图

什么是桑基气泡图?

桑基气泡图将桑基图的流动路径和气泡图的数量表现结合起来,能够同时展示数据之间的流动关系和每个类别的相对大小。

该图结合了桑基图和气泡图的特点。左侧为桑基图,展示每个pathway中包含的基因信息,流动路径表示基因在不同pathway之间的分布情况。右侧为常规的气泡图,气泡的大小表示每个pathway所属的基因数量,气泡的颜色则反映了该pathway的P值,通过颜色深浅区分统计显著性。这样,图表直观展示了基因在不同pathway中的分布及其统计显著性。

绘图前的数据准备

demo数据可以在这里下载

http://r2omics.cn/res/demodata/sankeyBubble.txt

这段表格包含了富集分析结果的相关数据,其中每一列代表不同的指标。下面逐个解释各列的含义:

  1. TermID:这是每个富集条目对应的唯一标识符。

  2. Term:这是与”TermID”对应的富集项的名称或描述。

  3. fg_term_num:前景基因集中实际与该富集项相关的基因数目。

  4. Ratio:该列表示前景基因集中富集项相关基因数量与背景基因集中富集项相关基因数量的比值。

  5. PValue:P值是用于评估该富集项是否具有统计显著性的值。

  6. IDs:该条目下包含哪些基因

R语言如何绘制桑基气泡图

# 代码来源:https://www.r2omics.cn/
library(tidyverse)
library(ggalluvial)
library(patchwork)
library(ggstyle) # 开发版安装方式devtools::install_github("sz-zyp/ggstyle")

# 读取数据
df = read.delim("http://r2omics.cn/res/demodata/sankeyBubble.txt")

# 整理数据
dfLong = df %>%
  separate_rows(IDs,sep = ",") %>%
  mutate(Term = factor(Term)) %>%
  mutate(IDs = factor(IDs))

# 准备桑基图数据
dfSankey = to_lodes_form(dfLong %>% select(c("IDs","Term")),
                       key = "x",
                       axes = c(1,2)) %>%
  mutate(flowColor = rep(dfLong$Term,2))

# 绘制桑基图
sankeyPlot=ggplot(data = dfSankey,
       aes(x = x,
           stratum = factor(stratum,levels = unique(stratum)),
           alluvium = alluvium,
           y = 1,
           label = stratum,
           fill = stratum
           )) +
  scale_y_discrete(expand = c(0, 0)) +
    geom_flow(aes(fill = flowColor),alpha = 0.3, width = 0, knot.pos = 0.1) +
    geom_stratum(width = 0.05, color = "white") +
    geom_text(stat = "stratum", aes(label = after_stat(stratum)), size = 3,
              hjust = 1, nudge_x = -0.03) +
    guides(fill = FALSE, color = FALSE) +
    theme_minimal() +
    labs(title = "", x = "", y = "") +
    theme(
      axis.text.x = element_blank(),
      axis.ticks.x = element_blank(),
      plot.margin = unit(c(0, 0, 0, 0), units = "cm")
      )+
  scale_x_discrete(expand = c(0.2, 0, 0, 0))+
  ggstyle::scale_fill_sci(palette="d3.category20")

# 准备气泡图数据
bubbleDf = df %>%
  mutate(Term = factor(Term,levels = rev(df$Term))) %>%
  arrange(Term) %>%
  mutate(Term_num = cumsum(Count) - Count / 2)

# 绘制气泡图
dot_plot <- ggplot(bubbleDf, aes(x = Ratio, y = Term_num,color=PValue)) +
  geom_point(aes(size = Count)) +
  scale_y_continuous(expand = c(0, 0),limits =c(0,sum(bubbleDf$Count,na.rm = T)))+
  scale_color_gradient(low = "red", high = "#1000ee") +
  scale_radius(
    range=c(2,5),
    name="Size")+
  guides(
    color = guide_colorbar(order = 1),        # 决定图例的位置顺序
    size = guide_legend(order = 2)
  )+
  theme_bw() +
  labs(size = "Count", color = "PValue", y = "", x = "Ratio") +
  theme(
    axis.text.y = element_blank(),
    axis.ticks.y = element_blank(),
    axis.title.y = element_blank(),
    plot.margin = unit(c(0, 0, 0, 0), "inches"),
    panel.grid = element_blank()
  )

# 合并桑基图和气泡图
sankeyPlot + dot_plot +
  plot_layout(widths = c(2, 1))