在stat_summary中使用position_dodge获取均值和置信区间?

时间:2016-12-23 02:14:19

标签: r ggplot2

我试图显示两组数据。我使用ggplot2包来绘制数据图表,并使用stat_summary()获取数据图中的点估计值(平均值)和90%CI。我所希望的是,平均值和置信区间被构造在表示数据分布的点的右侧。目前,stat_summary()只会将均值和CI强加于分布之上。

以下是我正在使用的数据示例:

set.seed(9909)
Subjects <- 1:100
values <- c(rnorm(n = 50, mean = 30, sd = 5), rnorm(n = 50, mean = 35, sd = 8))
data <- cbind(Subjects, values)
group1 <- rep("group1", 50)
group2 <- rep("group2", 50)
group <- c(group1, group2)
data <- data.frame(data, group)
data

这就是我目前的ggplot2代码的样子(分布为平均值,每组覆盖90%CI):

ggplot(data, aes(x = group, y = values, group = 1)) +  
geom_point() + 
stat_summary(fun.y = "mean", color = "red", size = 5, geom = "point") +
stat_summary(fun.data = "mean_cl_normal", color = "red", size = 2, geom = "errorbar", width = 0, fun.args = list(conf.int = 0.9)) + theme_bw()

是否可以将position_dodge的平均值和置信区间置于各自组的右侧?

1 个答案:

答案 0 :(得分:6)

您可以使用position_nudge

ggplot(data, aes(x = group, y = values, group = 1)) +  
  geom_point() + 
  stat_summary(fun.y = "mean", color = "red", size = 5, geom = "point",
               position=position_nudge(x = 0.1, y = 0)) +
  stat_summary(fun.data = "mean_cl_normal", color = "red", size = 2, 
               geom = "errorbar", width = 0, fun.args = list(conf.int = 0.9),
               position=position_nudge(x = 0.1, y = 0)) + 
  theme_bw()

enter image description here