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

ggplot2:y轴非计数/频率时分组条形图错位问题求助

解决方案

针对你遇到的问题,有两种可行的解决办法:

方法一:使用position_dodge2并指定stat="identity"

你之前用position_dodge2报错是因为没加stat="identity"——geom_bar默认会统计分组数量(stat="count"),这时候不需要指定y轴变量,而你要展示的是y=Time的具体数值,必须明确stat="identity"。结合preserve="single"可以让所有条形宽度保持一致,不会因为某组缺失类别而变宽。

修正后的代码:

p <- ggplot(d, aes(x = AgeGroup, y = Time, fill = Gender)) +
  geom_bar(
    stat = "identity",
    position = position_dodge2(preserve = "single", padding = 0.1), # padding调整条形间距
    width = 0.7
  ) +
  scale_fill_manual(values = c('#2A800A','#9CDC46'))
p

方法二:补全缺失的分组组合

先通过补全数据,让每个AgeGroup都包含所有Gender的水平(缺失的设为NA),再用position_dodge就能正常保持条形宽度一致,na.rm=TRUE会自动隐藏NA对应的条形。

需要用到tidyr包的complete函数:

library(tidyr)
# 补全AgeGroup和Gender的所有组合,缺失的Time设为NA
d_complete <- d %>%
  complete(AgeGroup, Gender, fill = list(Time = NA))

# 绘制图形
p <- ggplot(d_complete, aes(x = AgeGroup, y = Time, fill = Gender)) +
  geom_bar(
    stat = "identity",
    position = position_dodge(width = 0.7),
    na.rm = TRUE # 移除NA对应的条形
  ) +
  scale_fill_manual(values = c('#2A800A','#9CDC46'))
p

两种方法都能解决你遇到的“缺失类别时条形过宽”的问题,按需选择即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 03:05:10