使用 ggplot2 显示点和水平线(段)的均值

cbr*_*rnr 2 r ggplot2

我想绘制三组数据。具体来说,我想显示单个数据点,包括三组的平均值。这是我到目前为止所拥有的:

library(ggplot2)

df <- data.frame(group=rep(c("A", "B", "C"), each=10), value=rnorm(30))

ggplot(data=df, mapping=aes(x=group, y=value)) +
    geom_point() +
    stat_summary(fun="mean", geom="point", color="red", size=5) +
    stat_summary(fun="mean", geom="segment", mapping=aes(xend=..x.. + 0.25, yend=..y..))
Run Code Online (Sandbox Code Playgroud)

这会产生下图:

这就是我所拥有的

但是,我希望水平线段从每组平均值的左侧开始,而不是从中心开始。我尝试指定mapping=aes(x=..x.. - 0.25, xend=..x.. + 0.25, yend=..y..),但这只会给我一个错误:

Error: stat_summary requires the following missing aesthetics: x
Run Code Online (Sandbox Code Playgroud)

我不明白为什么我不能..x..用来指定x美学,而它适用于xend一个。

知道如何使水平线段围绕组中心对称吗?

Duc*_*uck 5

试试这个(也许不是最优雅的解决方案):

library(ggplot2)

df <- data.frame(group=rep(c("A", "B", "C"), each=10), value=rnorm(30))

ggplot(data=df, mapping=aes(x=group, y=value)) +
  geom_point() +
  stat_summary(fun="mean", geom="point", color="red", size=5) +
  stat_summary(fun="mean", geom="segment", mapping=aes(xend=..x.. - 0.25, yend=..y..))+
  stat_summary(fun="mean", geom="segment", mapping=aes(xend=..x.. + 0.25, yend=..y..))
Run Code Online (Sandbox Code Playgroud)

电子支票