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

如何提取ComplexHeatmap对应mtx的配色并应用于ggplot?

实操步骤

1. 提取各簇对应的十六进制颜色码

ComplexHeatmap的调色板mypal对应0-1的数值区间,先建立数值到颜色的映射关系:

library(ComplexHeatmap)
# 用colorRamp2生成映射函数,把0-1拆成和mypal长度匹配的区间
color_mapper <- colorRamp2(seq(0, 1, length.out = length(mypal)), mypal)

接着根据你的mtx矩阵确定每个簇的代表数值(比如Sender矩阵取每行均值,或直接用矩阵中对应簇的目标值),生成簇与颜色的对应向量:

# 这里假设mtx的行对应簇,取每行均值作为该簇的代表得分,可按需调整
cluster_scores <- rowMeans(mtx)
# 生成每个簇的精确十六进制颜色
cluster_colors <- color_mapper(cluster_scores)
# 给颜色向量加上簇名,方便后续调用
names(cluster_colors) <- rownames(mtx)

现在cluster_colors里就是各簇对应的颜色码,比如clust_3的Sender颜色直接取cluster_colors["clust_3"]即可。

2. 将mtx矩阵的数值替换为颜色码

用上面的映射函数批量处理整个矩阵:

mtx_colored <- apply(mtx, c(1,2), function(x) color_mapper(x))

处理后mtx中的每个数值都会被替换成对应的十六进制颜色字符串。

3. 在ggplot中应用这些颜色

如果要给同簇的Sender/Receiver设置深浅色(比如Sender用原颜色,Receiver用浅色版),可以先写个调亮度的小函数,再生成颜色映射:

library(ggplot2)
# 定义调浅颜色的函数,factor值越大颜色越浅
lighten_color <- function(color, factor = 0.3) {
  rgb_vals <- col2rgb(color)
  rgb_vals <- rgb_vals + (255 - rgb_vals)*factor
  rgb(rgb_vals[1], rgb_vals[2], rgb_vals[3], maxColorValue = 255)
}

# 生成Receiver的浅色版颜色
receiver_colors <- sapply(cluster_colors, lighten_color)
# 合并Sender和Receiver的颜色,命名格式为"簇名_Sender"/"簇名_Receiver"
color_map <- c(cluster_colors, receiver_colors)
names(color_map) <- c(paste0(names(cluster_colors), "_Sender"), paste0(names(receiver_colors), "_Receiver"))

# 假设绘图数据框为plot_df,包含cluster、role(Sender/Receiver)等列
ggplot(plot_df, aes(x = x_axis, y = y_axis, color = paste0(cluster, "_", role))) +
  geom_point(size = 3) +
  scale_color_manual(values = color_map) +
  theme_bw()

如果只想单独指定clust_3的颜色,直接在scale_color_manual中手动传值:

ggplot(plot_df, aes(x = x_axis, y = y_axis, color = interaction(cluster, role))) +
  geom_point(size = 3) +
  scale_color_manual(values = c(
    "clust_3.Sender" = cluster_colors["clust_3"],
    "clust_3.Receiver" = lighten_color(cluster_colors["clust_3"]),
    # 其他簇颜色按需补充
  )) +
  theme_bw()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 09:33:11