iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🐕

[Plot] [ComplexHeatmap] Extracting genes for each combination pattern from an UpSet plot

に公開
2025/08/08

This article uses the data from the UpSet plot I wrote about here. In the source link, I used the UpSet plot from the ComplexHeatmap package to visualize how much genes characteristic of cell sets (clusters) overlap or are independent of other clusters.
https://zenn.dev/rchiji/articles/0cdf3fec190c31

Extracting elements for each combination pattern

After visualizing with an UpSet plot, you might want to check the genes for each pattern (e.g., those unique to one cluster, those shared between cluster 2 and 3, etc.).

To extract those belonging to only one cluster, you can perform setdiff between the i-th element of deg_list and the others as shown below, but writing code for all other patterns is cumbersome.

# Prepare an empty list
unique_deglist <- list()

for(i in seq(deg_list)){
  # Perform setdiff between the i-th element of deg_list and the others, and save the result to the list
  unique_deglist[[i]] <- Reduce(f = setdiff, x = c(deg_list[i], deg_list[-i]))
}

names(unique_deglist) <- names(deg_list)


extract_comb

ComplexHeatmap provides the extract_comb() function to retrieve elements of a specific pattern. To use it, you specify a pattern using the comb_name= argument, which requires a binary code string of 0s and 1s.

You can check the binary codes for each pattern using the comb_name function.

comb_name(mt)

Setting readable=TRUE converts the binary codes into something more human-readable. It's still a bit hard to see, though.

Let's try extracting elements by specifying a pattern code. This corresponds to the part "(!cluster_0)&cluster_3&cluster_1&(!cluster_2)&cluster_4&cluster_5&(!cluster_6)". In other words, we are looking at genes shared across clusters 3, 1, 4, and 5.

extract_comb(m = mt, comb_name = "0110110")


Extracting elements for all patterns

Here is an example of grouping genes for each pattern code.

# Get the list of pattern codes
patterns <- comb_name(m = mt)

# Prepare an empty list and assign names
extract_genes <- vector(mode = "list", length = length(patterns))
names(extract_genes) <- patterns # You could also use names(extract_genes) <- comb_name(m = mt, readable = T)

# Extract with extract_comb for each pattern code and save to the list
for(i in patterns){
  extract_genes[[i]] <- extract_comb(m = mt, comb_name = i)
}


Furthermore, it is easier to handle if you sort the list by the length of its elements. By applying unlist(), you can create a gene vector rearranged according to the pattern order.

# Sort in descending order using the results of repeatedly applying the length function to the list with sapply
extract_genes <- extract_genes[order(sapply(extract_genes, length), decreasing = T)]



By the way, you can summarize each gene, its pattern code, and the number of overlaps with others into a data frame as follows.

# Repeatedly apply a function to create a data frame for gene names and pattern codes
tmp <- mapply(function(x, y){
  df <- data.frame(genes = x,  # Extract gene vector from the list containing gene vectors
                   code = rep(y, times = length(x)) # Repeat the list name (pattern code) for the number of elements in the gene vector
  )
  return(df)
  },
  x = extract_genes,
  y = names(extract_genes),
  SIMPLIFY = F # Output results as a list
  )

# Combine list elements vertically with rbind
genes_df <- do.call(rbind, tmp)
rownames(genes_df) <- genes_df$genes

# Use the str_count function to find the number of 1s in the pattern code.
genes_df$num_overlap <- stringr::str_count(string = genes_df$code, pattern = "1")


Providing the degree of overlap with other clusters as heatmap annotations

I will show an example of visualizing how specific the top DEGs (Differentially Expressed Genes) of each cluster are by using the pattern code information from the UpSet plot.

# Scale the expression data for Heatmap
seurat_object <- ScaleData(object = seurat_object, features = rownames(seurat_object))
# Get the order of clusters by the number of unique DEGs
unique_deglist <- list()
for(i in seq(deg_list)){
  unique_deglist[[i]] <- Reduce(f = setdiff, x = c(deg_list[i], deg_list[-i]))
}
names(unique_deglist) <- names(deg_list)
cluster_order <- names(unique_deglist[order(sapply(unique_deglist, length), decreasing = T)])

## Annotation data
anno <- seurat_object@meta.data
anno <- anno[,"Cluster", drop = FALSE]

## color setting
library(RColorBrewer)

cluster_size <- length(unique(anno$Cluster))
cluster_color <- scales::hue_pal()(cluster_size)
names(cluster_color) <- unique(anno$Cluster)

col_fun = circlize::colorRamp2(breaks = seq(cluster_size),
                               colors = rev(brewer.pal(n = cluster_size, name = "Spectral"))
                               )

## column order (Order of clusters with many unique DEGs)
anno$Cluster <- factor(anno$Cluster, levels = cluster_order)
anno <- arrange(anno, Cluster)

## Expression matrix
mat <- pbmc@assays$RNA@scale.data[rownames(genes_df), rownames(anno)]
mat <- as.matrix(mat)

## curated_gene label position
# Look at the top 5 genes for each cluster based on average log2FC.
curated_genes <- 
  deg %>%
  group_by(cluster) %>%
  top_n(n = 5, wt = avg_log2FC)
curated_genes <- unique(curated_genes$gene)

lab_position <- which(rownames(mat) %in% curated_genes)
lab_final <- rownames(mat)[lab_position]

## Annotation object
rowAnno <- rowAnnotation(num_overlap = anno_simple(genes_df$num_overlap,
                                                   col = col_fun,
                                                   width = unit(2,"mm"),
                                                   ),
                         show_annotation_name = FALSE
                         )

topAnno <- HeatmapAnnotation(df = anno,
                             show_annotation_name = FALSE,
                             col = list(Cluster = cluster_color))

## Heatmap
ht <- Heatmap(matrix = mat,
              cluster_rows = F,
              cluster_columns = F,
              show_column_names = F,
              show_row_names = F,
              col = circlize::colorRamp2(breaks = c(-3,0,3), colors = c("magenta","black","yellow")),
              heatmap_legend_param = list(title = "Scaled expression", at = seq(-3, 3, 1)),
              top_annotation = topAnno,
              left_annotation = rowAnno,
              column_split = anno$seurat_clusters,
              use_raster = TRUE,
              raster_quality = 5,
              raster_by_magick = FALSE, # --> If the "magick" package is present, it will be over-rasterized.
              )

lgd <- Legend(title = "No. overlap",
              col_fun = col_fun,
              at = seq(0, cluster_size, by = 2))

draw(ht, annotation_legend_list = list(lgd))

It can be seen that just because a gene is a top DEG does not necessarily mean it is cluster-specific.

Discussion