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

ggplot堆叠柱状图按Volume分组的实现问题求助

ggplot堆叠柱状图按Volume分组的实现问题求助

你好呀!我看你现在卡在ggplot堆叠柱状图的分组设置上了——想把Volume作为x轴Donor下的分组,但用group=Volume和position="fill"配合没达到预期效果对吧?我来帮你梳理下怎么调整~

你的需求回顾

你有三个分类变量,想这样可视化:

  • x轴展示Donor
  • 用分面(facet_wrap)展示Fraction
  • 在每个Donor下,按Volume分组展示堆叠柱状图(每个分组内是不同name的堆叠占比)

现有数据预览

你提供的数据集前6行:

head(dat_test)

Sample.ID  Kit Fraction Volume Donor    input reads_without_adapter short_reads UniVec_contaminants   rRNA
1 SV18860_0151 Mini Exosomal  250uL    D1  4502415                 60886     2003473              453080 255238
2 SV18860_0152 Mini Exosomal  250uL    D2 12377507                178344     4913533              303846 207784
3 SV18860_0153 Mini Exosomal  250uL    D3  5709522                 71621     1768752              512376 415050
4 SV18860_0154 Mini Exosomal  500uL    D1  3698808                 47131     1848724              617541  70741
5 SV18860_0155 Mini Exosomal  500uL    D2  8721473                 97316     4907378              392534  74877
6 SV18860_0156 Mini Exosomal  500uL    D3  5955653                 74085     3228077              747945 139265

长格式数据结构(部分):

dput(dat_test_lng)
structure(list(Sample.ID = c("SV18860_0151", "SV18860_0151",...), row.names = c(NA, -48L), class = c("tbl_df", "tbl", "data.frame"))

现有代码与问题

你当前的代码是:

ggplot(dat_test_lng %>% filter(Kit=="Mini"), aes(fill=name, y=value, x=Donor,group=Volume)) +
geom_bar(position="fill", stat="identity") +
facet_wrap(~ Fraction)

问题在于:group=Volume只是告诉ggplot分组逻辑,但x轴还是单一的Donor,导致不同Volume的堆叠柱直接重叠在一起,看不到分组效果。

解决方案

要实现“同一个Donor下,不同Volume的堆叠柱并排展示”的效果,咱们可以用position_filldodge()这个参数——它能同时实现堆叠(按fill变量)和分组并排(按group变量),完美适配你的需求:

方案1:保留Donor为x轴,分组并排堆叠柱

library(ggplot2)

ggplot(dat_test_lng %>% filter(Kit == "Mini"), 
       aes(fill = name, y = value, x = Donor, group = Volume)) +
  geom_bar(position = position_filldodge(width = 0.8), stat = "identity") +
  facet_wrap(~ Fraction) +
  labs(x = "Donor", y = "Proportion", fill = "Read Category") +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

这个代码会让每个Donor下的不同Volume堆叠柱并排,同时每个柱子内部按name堆叠显示占比,完全符合你想要的视觉结构。

方案2:将Donor+Volume作为x轴元素

如果你想更直观地看到每个分组对应的Volume,也可以把x轴设置为Donor和Volume的组合,直接展示每个组合的堆叠占比:

ggplot(dat_test_lng %>% filter(Kit == "Mini"), 
       aes(fill = name, y = value, x = interaction(Donor, Volume))) +
  geom_bar(position = "fill", stat = "identity") +
  facet_wrap(~ Fraction) +
  scale_x_discrete(labels = function(x) gsub("\\.", "\n", x)) +
  labs(x = "Donor & Volume", y = "Proportion", fill = "Read Category") +
  theme(axis.text.x = element_text(angle = 0, hjust = 0.5))

这里用interaction()把两个变量合并成x轴元素,再用scale_x_discrete()调整标签换行,让内容更易读。

你可以根据自己的视觉偏好选择其中一种方案,应该就能达到你想要的效果啦!

备注:内容来源于stack exchange,提问作者user20453870

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.20 08:19:51