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

如何为来自独立表预测值的geom_line添加标准差误差棒?

问题原因

全局ggplot(aes())里设置了y = my_y,geom_errorbar会继承这个映射,但你的data.frame.2里没有my_y列,所以报错。而geom_line因为显式指定了y = .fitted,覆盖了全局的y映射,所以能正常运行。

两种修改方案

方案一:给geom_errorbar显式指定y值

在geom_errorbar的aes里加上y = .fitted,和geom_line一样覆盖全局的y映射:

data.frame.1 %>%
  ggplot(aes(my_x, col = my_groups)) +
  geom_point(aes(y = my_y)) +
  geom_line(
    data = data.frame.2,
    aes(y = .fitted)
  ) +
  geom_errorbar(
    data = data.frame.2,
    aes(
      y = .fitted,
      ymin = .fitted - SD.fitted,
      ymax = .fitted + SD.fitted
    )
  )

方案二:把y映射移到geom_point里

直接从全局aes中移除y = my_y,只在geom_point里指定,这样其他图层不会继承这个有问题的映射:

data.frame.1 %>%
  ggplot(aes(my_x, col = my_groups)) +
  geom_point(aes(y = my_y)) +
  geom_line(
    data = data.frame.2,
    aes(y = .fitted)
  ) +
  geom_errorbar(
    data = data.frame.2,
    aes(
      ymin = .fitted - SD.fitted,
      ymax = .fitted + SD.fitted
    )
  )

两种方案都能解决问题,方案二更清晰,避免全局映射带来的冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 01:45:36