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

如何调整R语言ggplot堆叠直方图的堆叠位置?

Adjusting Stack Position for Your ggplot Histogram

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:22:49