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

R语言问题:设置精确Y轴范围后分组柱状图仅显示误差条

问题分析与解决

核心问题原因

  1. 语法错误导致美学映射失效:原代码中aes()的括号过早闭合,y和fill参数未被纳入ggplot的美学映射,geom_bar无法获取Y轴数值,因此无法绘制柱形,同时触发缺失值警告。
  2. 变量名不匹配:误差条中使用wish_t1作为均值变量,但aes里的Y轴映射是wish_for_partner_t1,两者不一致会导致数据逻辑混乱。

修正后的代码

ggplot(wish_c, aes(
  x = factor(esnonrom_t,
             levels = c("0", "1"),
             labels = c("Received no support (n = 89)", "Received support (n=795)")),
  y = wish_for_partner_t1,  # 替换为你的分组均值变量,确保和误差条中一致
  fill = factor(sex_gen,
                levels = c("0", "1"),
                labels = c("Men (n=427)", "Women(n=457)"))
)) +
  geom_bar(position = position_dodge(), stat = "identity") +
  geom_errorbar(aes(ymin = wish_for_partner_t1 - se, ymax = wish_for_partner_t1 + se),
                width = .2,
                position = position_dodge(.9)) +
  scale_y_continuous("Wish (1-5)", limits = c(1, 5), breaks = seq(1, 5, by = 1)) +
  theme_classic() +
  scale_fill_brewer(palette = "Greys") +
  labs(
    x = "Emotional support received beyond the romantic relationship",
    fill = "Gender",
    title = "Wish by gender and emotional support"
  )

额外注意事项

  • 确认wish_c数据是分组汇总后的结果(每个性别-支持组一行,包含均值wish_for_partner_t1和标准误se),否则stat="identity"无法正确绘制柱形。
  • 如果仍有缺失值警告,检查数据中是否存在wish_for_partner_t1为NA的行,或均值超出1-5范围的异常值,可通过filter(!is.na(wish_for_partner_t1), wish_for_partner_t1 >=1, wish_for_partner_t1 <=5)过滤。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 18:53:13