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

geom_col使用position_stack警告及自定义堆叠条形图实现咨询

解决方法

原代码的问题出在数据构造逻辑上:你用rep(df$value, times = c(2,1))生成的x列是重复数值,导致geom_col在不同x轴位置绘制独立柱子,根本没法实现堆叠,这也是警告position_stack() requires non-overlapping x intervals`的原因。

下面给两种能实现需求且消除警告的方案:

方案一:用geom_col直接堆叠

这种方法最简洁,直接基于原始df数据,将x设为固定值(确保所有分段在同一位置堆叠),再通过position="stack"实现比例分配:

library(ggplot2)
library(dplyr)

df <- data.frame (group  = c("east", "west"),
                  value = c(1/3, 2/3)
)

# 横向堆叠(宽度占比1/3和2/3)
ggplot(df, aes(x = 1, y = value, fill = group)) +
  geom_col(position = "stack", color = "white", linewidth = 0.1, width = 1) +
  coord_flip() +
  scale_y_continuous(limits = c(0, 1)) +
  theme_void()

# 若要纵向堆叠(高度占比1/3和2/3),去掉coord_flip()即可

方案二:用geom_rect精确控制区间

如果需要更灵活的位置控制,比如自定义左右边界,可以先计算每个分段的x轴起止范围,再用geom_rect绘制:

df <- df %>%
  # 计算每个分组的x轴起止点
  mutate(xmin = cumsum(lag(value, default = 0)),
         xmax = cumsum(value))

ggplot(df, aes(xmin = xmin, xmax = xmax, ymin = 0, ymax = 1, fill = group)) +
  geom_rect(color = "white", linewidth = 0.1) +
  scale_x_continuous(limits = c(0, 1)) +
  scale_y_continuous(limits = c(-5, 5)) + # 保留你原代码的y轴范围
  theme_void()

两种方案都能实现east占1/3宽度、west占2/3宽度的堆叠效果,同时彻底消除警告。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 19:58:40