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

如何给ggplot堆叠条形图添加类似ComplexHeatmap的分组颜色条注释?

给ggplot堆叠条形图添加左侧分组颜色注释(类似ComplexHeatmap的left_annotation)

我们可以通过创建分组注释数据,结合geom_rect在图表左侧绘制颜色条,实现类似ComplexHeatmap左侧注释的效果。以下是修改后的完整代码:

library(ggplot2)

# 原始数据,修正cbind导致的类型问题
test <- data.frame(
  a = c(1, 1, 2, 3),
  b = 1:4,
  c = as.character(1:4)
)

# 准备左侧注释数据:为每个a分组分配对应颜色
anno_df <- data.frame(
  a = unique(test$a),
  # 自定义分组颜色,可按需修改
  anno_color = c("#E69F00", "#56B4E9", "#009E73")
)

# 绘制图表
ggplot(test) +
  # 绘制左侧分组颜色注释条
  geom_rect(data = anno_df,
            aes(xmin = -0.2, xmax = 0, ymin = a - 0.4, ymax = a + 0.4, fill = I(anno_color)),
            inherit.aes = FALSE) +
  # 原始堆叠条形图
  geom_bar(aes(x = a, y = b, fill = c), stat = "identity") +
  # 保留原有的透明汇总边框
  geom_bar(aes(x = a, y = b, group = a),
           stat = "summary", fun = sum,
           fill = "transparent", color = "black") +
  coord_flip() +
  # 扩展x轴范围,避免注释被裁剪
  xlim(-0.2, max(test$a) + 0.4) +
  # 调整主题优化布局
  theme(
    axis.title.y = element_text(margin = margin(r = 10)),
    panel.grid = element_blank()
  )

关键说明:

  • anno_df:专门存储每个a分组对应的注释颜色,可根据实际分组数量自定义颜色列表。
  • geom_rect:通过xmin/xmax控制注释条宽度,ymin/ymax匹配分组在y轴的位置,fill = I(anno_color)直接调用自定义颜色。
  • xlim:扩展x轴范围,确保左侧注释完整显示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 18:49:58