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

如何用ggplot2基于归一化相对丰度数据绘制等高堆叠条形图?

绘制归一化数据的等高堆叠条形图(df2适配)

需求背景

需要基于范围0-1的归一化数据绘制等高堆叠条形图,处理df1时已成功实现,处理df2时堆叠条形图高度不一致,需调整代码。

df1成功代码

library(ggplot2)
p<-ggplot(data=df1, aes(x=ids, y=value, fill=variable)) +
  geom_bar(stat="identity") + theme(
    axis.title.x = element_text(color="black", size=14, face="bold"),
    axis.title.y = element_text(color="black", size=14, face="bold")
  )
p + labs( y= "Relative_abundance", x= "Patients_ids") + scale_fill_discrete(name = "Phylum")+ coord_flip()

df2问题代码(高度不一致)

library(ggplot2)
p<-ggplot(data=df2, aes(factor(state_time))) +
  geom_bar (aes(group = variable, fill=variable)) + theme(
    axis.title.x = element_text(color="black", size=14, face="bold"),
    axis.title.y = element_text(color="black", size=14, face="bold")
  )
p + labs( y= "Relative_abundance", x= "Soil_Types") + scale_fill_discrete(name = "Taxon")+ 
   theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))+ coord_flip()

修改方案及代码

问题根源是df2的代码未指定y轴的归一化数值映射,geom_bar默认执行计数统计,而非使用你的归一化value列。需参照df1的逻辑调整:

  1. 在ggplot的aes中添加y=value,指定使用归一化数值
  2. 为geom_bar设置stat="identity",确保直接使用原始数值堆叠
  3. 添加scale_y_continuous(limits = c(0,1))固定y轴范围0-1

修改后的完整代码:

library(ggplot2)
p<-ggplot(data=df2, aes(x=factor(state_time), y=value, fill=variable)) +
  geom_bar(stat="identity") + 
  theme(
    axis.title.x = element_text(color="black", size=14, face="bold"),
    axis.title.y = element_text(color="black", size=14, face="bold"),
    axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)
  )
p + labs(y= "Relative_abundance", x= "Soil_Types") + 
  scale_fill_discrete(name = "Taxon") +
  scale_y_continuous(limits = c(0, 1)) +
  coord_flip()

说明

  • 确保df2的结构和df1一致:包含state_time(分类x轴)、value(0-1的归一化值)、variable(分组填充列)三列
  • stat="identity"是关键,它告诉ggplot直接使用y=value的数值,而非自动计数
  • scale_y_continuous(limits = c(0,1))强制y轴锁定在0到1的范围,保证所有堆叠条高度统一

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 11:12:53