如何用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:
1. Grouped Bars (Most Recommended)
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 overlappinggeom_col()is more intuitive here thangeom_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
alphaparameter 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

