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

R语言ggplot堆叠相对丰度柱状图添加百分比标签求助

堆叠柱状图添加百分比标签解决方案

你已经完成了相对丰度的标准化处理,无需额外计算占比,直接通过geom_text的堆叠位置匹配即可实现百分比标签居中显示,修改后的完整代码如下:

OA_comm <- OA_rare %>%  
  tax_glom(taxrank = "Phylum")  %>% 
  transform_sample_counts(function(x) {x/sum(x)} ) %>% 
  psmelt() %>%
  filter(Abundance > 0.01)   %>% 
  arrange(Phylum)


OA_comm_plot <- ggplot(OA_comm,aes(x=pH_treatment,y=Abundance,fill=Phylum))+ 
  geom_bar(stat="identity",position="fill") +
  # 新增百分比标签层
  geom_text(aes(label = paste0(round(Abundance * 100, 1), "%")),
            position = position_stack(vjust = 0.5),
            size = 3,
            color = "white") +
  # 可选:将y轴刻度转换为百分比格式,显示更统一
  scale_y_continuous(labels = scales::percent) + 
  ylab("Relative Abundance")

OA_comm_plot 

参数说明

  • position = position_stack(vjust = 0.5):自动匹配堆叠柱的分层位置,vjust=0.5表示标签垂直居中对齐到每个分类对应的堆叠区块
  • 标签格式可按需调整:如果要显示整数百分比,把round(Abundance * 100, 1)改成round(Abundance * 100)即可
  • 如果觉得标签过多拥挤,可设置阈值只显示高丰度标签,将label参数替换为label = ifelse(Abundance > 0.05, paste0(round(Abundance * 100, 1), "%"), "")即可隐藏丰度低于5%的标签

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 14:18:05