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

R语言堆叠直方图顶部添加临床元数据颜色标签的实现方法咨询

实现方案

该功能完全可以通过ggplot2实现,核心思路是在堆叠柱形图的上方叠加独立的色块/文字图层,通过控制图层的y轴位置实现柱顶标注行的效果,具体实现如下:

1 数据预处理

首先需要导入测试数据,同时固定样本的排序为你已得到的PCoA排序,避免绘图时R自动重排因子导致标注与柱形错位:

library(tidyverse)

# 导入物种丰度数据
abun <- read.table(text = "Pt  Streptococcus   Staphylococcus  Lactobacillus   Acinetobacter   Pseudomonas Bacillus
patient1    61.20    5.65    7.45    1.65    0.30    0.60
patient6    43.00    2.10   18.10    0.40    0.60    0.60
patient5    41.95    4.10   24.55    0.75    0.90    0.00
patient8    41.15   25.95    3.50    0.20    7.45    0.30
patient4    26.45   55.10    2.55    3.40    0.05    2.85
patient7    18.20   26.40    0.95   20.25    0.50    0.05
patient3    18.00   18.70   38.55    0.10   56.55    0.00
patient2     0.35    0.05    2.10    0.20    0.40   94.75", header = T, sep = "", stringsAsFactors = F)

# 导入临床元数据
meta <- read.table(text = "Pt Time
patient1    T1
patient2    T3
patient3    T4
patient4    T2
patient5    T2
patient6    T1
patient7    T1
patient8    T2", header = T, sep = "", stringsAsFactors = F)

# 固定样本顺序为PCoA排序结果
abun$Pt <- factor(abun$Pt, levels = unique(abun$Pt))
meta$Pt <- factor(meta$Pt, levels = levels(abun$Pt))

# 丰度数据转为长格式,匹配元数据
abun_long <- abun %>% 
  pivot_longer(-Pt, names_to = "Species", values_to = "Abundance") %>% 
  left_join(meta, by = "Pt")

2 绘图代码

通过叠加geom_tile实现标注色块,geom_text实现标注文字,调整y轴范围预留标注空间:

ggplot() +
  # 基础堆叠柱形图层
  geom_col(data = abun_long, aes(x = Pt, y = Abundance, fill = Species)) +
  # 柱顶标注色块层:y设为102,刚好在总丰度100的上方,height控制色块高度
  geom_tile(data = meta, aes(x = Pt, y = 102, fill = Time), height = 3) +
  # 可选:标注色块上方加文字说明
  geom_text(data = meta, aes(x = Pt, y = 106, label = Time), size = 3) +
  # 调整y轴范围,预留标注空间
  ylim(0, 110) +
  # 主题自定义
  theme_classic() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

3 扩展说明

如果需要添加多行临床标注(比如你提到的性取向、HIV感染状态两个维度),只要叠加多个geom_tile层,分别设置不同的y轴位置即可:

  • 第一组标注y设为102
  • 第二组标注y设为108
    即可形成多行并列的标注行,和目标论文中的展示样式完全一致。
    如果你的丰度数据是0-1范围的相对丰度,把对应的y值调整为1.02、1.08等数值即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 19:18:04