SD错误条不正确

时间:2015-08-14 13:12:17

标签: r ggplot2

嗨我的图中的错误条有问题。这是我的代码

library(ggplot2)
val1 <- sample(1:18)
val2 <- sample(20:50, 18)
mylet<-c("A", "B", "C")
time <-rep(mylet,times=6)
id<-rep(c("WT", "KO"), each=9)
x1 <- data.frame(id, time, val1, val2)
x1$id=factor(x1$id, c("WT","KO"))

cols = c(3,4)
df1  = transform(x1, mean=rowMeans(x1[cols]), sd=apply(x1[cols],1, sd))

p<-ggplot(data=df1, aes(x=as.factor(time), y=mean, fill=id)) +  
  geom_bar(position=position_dodge(), stat="identity", colour="black") +
  geom_errorbar(aes(ymin=mean-sd, ymax= mean+sd), width=0.2, position=position_dodge(0.9))
p

这是获得的数字

enter image description here

1 个答案:

答案 0 :(得分:2)

问题是,在变量df1中,您为每个(idtime)组合进行了多次测量(例如,对于id WT和时间A,您有相应的点数表示值13.0,30.5和15.0)。您需要决定如何处理此级别的复制,是否在图中表示它,或显示其上的统计信息。既然您知道实验设计的细节,而且这是您的数据,那么您应该是做出判断的人......

例如,对每个(idtime)组合的多个点进行平均:

library(plyr)
df2 <- ddply(df1, c("id", "time"), summarize, mean.overall = mean(mean), sd.overall = sd(mean))

然后通过以下方式绘图:

p <- 
    ggplot(data = df2, aes(x = as.factor(time), y = mean.overall, fill = id)) + 
    geom_bar(position = position_dodge(), stat = "identity", colour = "black") + 
    geom_errorbar(aes(ymin = mean.overall-sd.overall, ymax = mean.overall + sd.overall), width = 0.2, position = position_dodge(0.9))
p

将产生具有正确排列的误差条的图形。请记住,此处的统计数据是通过对每个(idtime)组合的3个点进行平均而获得的