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

如何用ggplot2绘制非叠加式堆叠条形图展示真实年龄数据

Ah, I see the issue here! position_stack() is built to sum up y-values within the same x-group, which is why you're seeing those inflated totals over 60 even though your maximum age is only 31 days. Since age is an independent metric for each life stage (there's no logical reason to add them together), we can adjust this with two tailored approaches depending on your desired visual:

This is the clearest way to display independent age values for each life stage. Instead of stacking, we'll place bars side-by-side using position_dodge():

library(ggplot2)

x <- data.frame(
  species = c("Alpha", "Alpha", "Alpha","Beta", "Beta", "Beta","Gamma", "Gamma", "Gamma"),
  lifestage = factor(c("infant", "juvenile", "adult", "infant", "juvenile", "adult", "infant", "juvenile", "adult"),
                     levels = c("infant", "juvenile", "adult")),
  age = c(10, 20, 30, 11, 21, 31, 9, 19, 29)
)

ggplot(x, aes(x = reorder(species, -age), y = age, fill = lifestage)) +
  geom_col(position = position_dodge(width = 0.8)) +  # geom_col is shorthand for geom_bar(stat="identity")
  coord_flip()
  • position_dodge(width = 0.8) ensures bars from different life stages sit side-by-side without overlapping
  • geom_col() is more intuitive here than geom_bar(stat="identity") since we're plotting precomputed values

2. Stacked Visual with Independent Heights (Less Intuitive but Possible)

If you really want the stacked vertical appearance but keep each bar's height as the true age (note: this will cause overlap since bars start at y=0), use position_identity() with transparency to distinguish stages:

ggplot(x, aes(x = reorder(species, -age), y = age, fill = lifestage)) +
  geom_col(position = position_identity(), alpha = 0.7) +
  coord_flip()
  • position_identity() keeps each bar in its original position (no summing or shifting)
  • The alpha parameter adds transparency so you can see overlapping bars

For most use cases, the grouped bar approach is better—it makes it easy to compare ages across life stages and species without visual confusion.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:36:49