You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R的UpSet图中添加交集基因标签以显示具体重叠基因?

解决UpSet图显示交集基因名称的方法

当基因集数量较多(>10组)时,UpSetR默认仅展示交集数量,要添加具体基因标签,可通过以下两种方法实现:

方法一:使用ComplexUpset包(推荐,基于ggplot2更灵活)

ComplexUpset是UpSet图的ggplot2拓展,支持自定义标注,适配多组基因集场景。

  1. 安装并加载依赖包
install.packages("ComplexUpset")
library(ComplexUpset)
library(ggplot2)
  1. 整理基因集数据
    将多个基因向量转换为data.frame格式,每行对应一个基因,每列标记该基因是否属于对应基因集:
# 示例基因集
gene_set1 <- c('Tmed9', 'Actb', 'Gapdh', 'Hsp90ab1')
gene_set2 <- c('Tmed9', 'Actb', 'Ppia', 'Rpl13a')
gene_set3 <- c('Tmed9', 'Gapdh', 'Ppia', 'Rps27a')

# 生成标准化数据框
all_genes <- unique(c(gene_set1, gene_set2, gene_set3))
gene_df <- data.frame(
  Gene = all_genes,
  Set1 = all_genes %in% gene_set1,
  Set2 = all_genes %in% gene_set2,
  Set3 = all_genes %in% gene_set3
)
  1. 绘制带基因标签的UpSet图
    先计算每个交集对应的基因列表,再在柱状图上方添加标签:
# 提取交集信息及对应基因
intersection_data <- upset_get_intersections(gene_df, c('Set1', 'Set2', 'Set3'))
intersection_data$gene_labels <- sapply(intersection_data$intersection, function(x) {
  # 提取当前交集的所有基因,用逗号分隔
  paste(gene_df$Gene[apply(gene_df[,x], 1, all)], collapse = ', ')
})

# 绘制UpSet图并添加标签
upset(gene_df, c('Set1', 'Set2', 'Set3'),
      base_annotations = list(
        '交集大小' = geom_bar(fill = 'steelblue') +
          geom_text(aes(label = gene_labels), vjust = -0.5, size = 3)
      )) +
  theme_minimal()

若基因名称过长导致重叠,可使用str_wrap自动换行:

intersection_data$gene_labels <- sapply(intersection_data$intersection, function(x) {
  genes <- gene_df$Gene[apply(gene_df[,x], 1, all)]
  paste(strwrap(paste(genes, collapse = ', '), width = 15), collapse = '\n')
})

方法二:UpSetR结合基础绘图手动添加标签

若坚持使用UpSetR,可提取交集数据后手动添加文本标注:

  1. 加载UpSetR并准备数据
library(UpSetR)
gene_list <- list(
  Set1 = gene_set1,
  Set2 = gene_set2,
  Set3 = gene_set3
)
  1. 提取交集信息
# 转换为UpSetR所需的二进制矩阵
upset_matrix <- fromList(gene_list)
# 获取交集的大小和对应分组
intersection_info <- upset:::get_intersections(upset_matrix, nsets = length(gene_list))
# 提取每个交集的基因
intersection_genes <- lapply(intersection_info$intersections, function(x) {
  rownames(upset_matrix)[apply(upset_matrix[,x], 1, all)]
})
# 转换为字符串格式
gene_labels <- sapply(intersection_genes, paste, collapse = ', ')
  1. 绘图并添加标签
# 绘制基础UpSet图
upset(gene_list, order.by = 'freq')
# 获取绘图坐标范围,调整标签位置
x_coords <- 1:length(gene_labels)
y_coords <- intersection_info$Sizes + max(intersection_info$Sizes)*0.05
# 添加基因标签
text(x = x_coords, y = y_coords, labels = gene_labels, cex = 0.7)

内容的提问来源于stack exchange,提问作者ramen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 05:55:17