错误栏的错误位置

时间:2016-07-05 10:10:12

标签: r ggplot2

我正在尝试使用多行创建一个绘图,并使用stat_summary定义平均值。当我申请geom_errorbar()时,其中一些被放置一段距离以表示指示,这意味着其中一些是“飞行”。发生了什么事?

谢谢!

我的代码:

    #First I add another data set with SE, SD and mean.
cdata <- ddply(data2, c("OGTT","Treatment"), summarise,
               N = sum(!is.na(Glucose)),
               mean = mean(Glucose, na.rm=TRUE),
               sd   = sd(Glucose, na.rm=TRUE),
               se   = sd / sqrt(N))


    #Then I merge it with my original data 
totalglu<-merge(data2,cdata)

#Then I make the ggplot
p<-ggplot(data=totalglu, aes(x = factor(OGTT), y = Glucose, group = StudyID, color=StudyID)) + 
  geom_line() +
  facet_grid(End.start ~Treatment)+ 
  stat_summary(aes(group = Treatment), geom = "point", fun.y = mean, shape = 16, size = 2) +
  theme(legend.position="none") +
  labs(x = "OGTT time points (min)",y= "Glucose (mmol/l)")+
  geom_errorbar(aes(ymin=mean-se,ymax=mean+se), width=.1, colour="black")
p

My plot with flying errorbars for a some of the points

1 个答案:

答案 0 :(得分:0)

在计算条形图时,您似乎没有使用End.start,但由于分面,stat_summary正在使用它。

尝试:

cdata <- ddply(data2, c("OGTT","Treatment","End.start"), summarise,
               N = sum(!is.na(Glucose)),
               mean = mean(Glucose, na.rm=TRUE),
               sd   = sd(Glucose, na.rm=TRUE),
               se   = sd / sqrt(N))


    #Then I merge it with my original data 
totalglu<-merge(data2,cdata)

#Then I make the ggplot
p<-ggplot(data=totalglu, aes(x = factor(OGTT), y = Glucose, group = StudyID, color=StudyID)) + 
  geom_line() +
  facet_grid(End.start ~Treatment)+ 
  stat_summary(aes(group = Treatment), geom = "point", fun.y = mean, shape = 16, size = 2) +
  theme(legend.position="none") +
  labs(x = "OGTT time points (min)",y= "Glucose (mmol/l)")+
  geom_errorbar(aes(ymin=mean-se,ymax=mean+se), width=.1, colour="black")
p

虽然没有实际的起始数据,但我不太确定data2的样子,或ddply如何影响事物。相反,我可能会建议完全跳过cdata,只使用:

ggplot(data=totalglu, aes(x = factor(OGTT), y = Glucose, group = StudyID, color=StudyID)) + 
  geom_line() +
  facet_grid(End.start ~Treatment)+ 
  stat_summary(aes(group = Treatment), fun.data = mean_cl_normal) +
  theme(legend.position="none") +
  labs(x = "OGTT time points (min)",y= "Glucose (mmol/l)")