求助:基于Kraken报告制作readsRooted占比的填充柱状图
解决方案
你的问题出在geom_bar()的默认行为上——它默认执行计数统计(stat="count"),而不是直接使用你提供的readsRooted数值。要实现按readsRooted占比的堆叠柱状图,按以下步骤操作即可:
1. 计算物种reads占比
先基于原始数据计算每个物种的reads数占总reads数的百分比:
library(dplyr) # 生成百分比列 df <- df %>% mutate(total_reads = sum(readsRooted), percent = (readsRooted / total_reads) * 100)
2. 绘制堆叠柱状图
使用geom_col()(等价于geom_bar(stat="identity"))直接调用数值,而非让ggplot自动计数:
library(ggplot2) ggplot(df, aes(x = taxRank, y = percent, fill = sciName)) + geom_col() + # 可选:添加百分比标签,让占比更直观 geom_text(aes(label = paste0(round(percent, 1), "%")), position = position_stack(vjust = 0.5), size = 3) + # 设置图表标签 labs(x = "分类等级", y = "占比 (%)", fill = "物种名称", title = "物种Reads占比分布") + theme_minimal()
原代码无效的原因
原代码ggplot(fam.kreport, aes(x = taxRank, fill = sciName)) + geom_bar()中,geom_bar()默认统计每个sciName的出现次数(这里每个物种仅1行数据,所以每个堆叠部分高度都为1),完全没有用到readsRooted的数值,因此无法反映实际的reads占比。
内容的提问来源于stack exchange,提问作者Mohamed Aziz Hadj Nasr
相关产品推荐
相关产品推荐

