如何调整R语言ggplot堆叠直方图的堆叠位置?
Hey there! Let's fix up that histogram stacking to match your target style. The default behavior of geom_histogram with a fill aesthetic stacks bars on top of one another, but we can tweak the position parameter to get the layout you want. Here are the two most common adjustments:
1. Side-by-Side (Dodged) Bars
If you want bars for each income group to sit next to each other instead of stacking, use position_dodge(). Adding preserve = "single" ensures bars stay the same width even if some age groups only have one income category:
ggplot(adult, aes(age, fill = income)) + geom_histogram(color = 'black', binwidth = 1, position = position_dodge(preserve = "single")) + theme_bw()
2. Percentage Stacked Bars
If you want each age group's bar to span 100% height (showing the proportion of each income group per age), use position_fill(). We'll also update the y-axis label to make it clear it's showing percentages:
ggplot(adult, aes(age, fill = income)) + geom_histogram(color = 'black', binwidth = 1, position = position_fill()) + theme_bw() + ylab("Percentage")
If your target style is something else (like a reversed stack or a custom offset), feel free to share more details, and we can refine the code further!
内容的提问来源于stack exchange,提问作者Abhishek Pokhrel

