用SE绘制条形图的简单方法

时间:2015-01-11 10:40:29

标签: r plyr

我希望有人可以帮助找到一个用错误条生成条形图的镜头。一般来说,我喜欢这个

# some dummy data
q <- setNames(data.frame(matrix(sample(100,400,T), nrow=20)), 
c("A","B","C","D","E","F","G","H","I","G","K","L","M","O","P","Q","R","S","T","U")) 

#I usually melt the data
library(reshape2)
a1 <- melt(q)

# summarize them
library(plyr)
a2 <- ddply(a1, c("variable"), summarise, mvalue = mean(value, na.rm=TRUE),
                                          medvalue = median(value, na.rm=TRUE),
                                          sd = sd(value, na.rm=TRUE),    
                                          n = sum(!is.na(value)),se = sd/sqrt(n))

#However, I got an error in generating se:
#Error in sd/sqrt(n) : non-numeric argument to binary operator

# then I plot the graph  
library(ggplot2)
ggplot(sum1, aes(x=variable, y=mvalue, fill=variable))+
 geom_bar(stat='identity', position='dodge')+
 geom_errorbar(aes(ymin=mvalue-sd,ymax=mvalue+sd))+
 scale_fill_grey()
 # here i used the sd instead of se 

为什么我收到se的错误?有没有办法保存所有这些步骤,以更智能的方式生成带错误条的条形图?

1 个答案:

答案 0 :(得分:1)

ddplydplyr

的阴影下几乎完全失效
library(dplyr)
a1$variable <- as.character(a1$variable)
a1  %>% 
  group_by(variable) %>%
  summarise(mvalue = mean(value, na.rm=TRUE),
            medvalue = median(value, na.rm=TRUE),
            sd = sd(value, na.rm=TRUE),    
            n = sum(!is.na(value)), se = sd/sqrt(n)) %>% 
  ggplot(., aes(x=variable, y=mvalue, fill=variable)) +
  geom_bar(stat='identity', position='dodge')+
  geom_errorbar(aes(ymin=mvalue-se, ymax=mvalue+se))+
  scale_fill_grey()