【问题标题】:ggplot2 wrong position of error bars over the barsggplot2错误条在条上的错误位置
【发布时间】:2016-08-04 10:36:26
【问题描述】:

我有问题。我将标准误差(se)用于我的误差线。我的误差线远高于我的误差线,我已经尝试将 ymin 和 ymax 放在 ggplot 本身中,但没有任何效果。

我的数据框如下所示:

  ID variable        se
1 A  14.340695 0.7917790
2 B  32.506312 0.9092173
3 C  7.279953 0.0444325

我使用了以下代码:

df$variable=as.numeric(as.character(df$variable))
limits<-aes(ymin=df$variable - df$se, ymax=df$variable + df$se)
r<-ggplot(df, aes(x=ID, y=factor(variable), fill=variable)) 
r + geom_bar(position=position_dodge(), stat="identity") + geom_errorbar(limits)

我不知道为什么 error_bars 的位置最终会比条本身高很多。

感谢您的帮助,非常感谢!

【问题讨论】:

  • 不要在aes中使用df$
  • 这并不能解决问题,但我对为什么不使用它很感兴趣。我是ggplot2的新手。你能@Roland 给我解释一下吗?
  • 因为在创建绘图时,aes 中指定的变量会在传递给 ggplot 或 geom 的 data 参数的 data.frame 内进行评估。如果您使用df$,它将从绘图代码之外的 data.frame 中获取它们。有时 ggplot2 会重新排序数据。结果,使用传递给 ggplot2 的 data.frame 评估的变量和来自 ggplot2 外部的变量不再排列。

标签: r ggplot2 errorbar


【解决方案1】:

这似乎与将 y 设置为因子有关。如果你删除它,它会起作用:

ggplot(df, aes(x=ID, y=variable, fill=variable)) + 
  geom_bar(stat="identity") +
  geom_errorbar(aes(ymin=variable-se, ymax=variable+se))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-24
    • 1970-01-01
    • 1970-01-01
    • 2023-01-29
    相关资源
    最近更新 更多