使用R

时间:2016-02-24 18:20:36

标签: r ggplot2 mean errorbar

我有以下数据:

a_ray<-c(12,13,14,15,16,16,14,14,15,16,16,16,23,14)
b_ray<-c(23,24,25,21,23,23,23,26,27,25,24,25,24,24)
c_ray<-c(45,32,34,36,48,32,31,34,49,50,58,56,58,32)
group<-c(0.12,0.28,0.29,0.36,0.15,0.65,0.54,0.28,0.08,0.14,0.03,0.06,0.09,0.25)
mydata<-cbind(a_ray,b_ray,c_ray,group)

我想为此数据集绘制平均值和误差线。 x轴的标签是:a_ray,b_ray和c_ray,y轴是这些光线的值(被调用&#34;光线值&#34;),还有一个变量&#34; Group&# 34;包含在我的数据中,我想在一个图表中绘制两行,一行约为&#34; Group&lt; 0.2&#34 ;,另一行约为&#34; Group&gt; = 0.2&#34;,预期图表如下:

enter image description here

1 个答案:

答案 0 :(得分:1)

在@scoa的帮助下,我终于解决了!

我的代码如下:

mydata<-as.data.frame(mydata)
mydata$groupvar<-cut(mydata$group,c(0,0.2,1))

mydata<-mydata[,-4]

library("reshape")
changedata <- melt(mydata,id=c("groupvar"),variable_name="Ray")

library("plyr")
arrangedata <- ddply(changedata, c("groupvar","Ray"), summarise,
               N    = length(value),
               mean = mean(value),
               sd   = sd(value),
               se   = sd / sqrt(N))

pd <- position_dodge(0.1)  #The errorbars overlapped, so use position_dodge to move them horizontally
ggplot(arrangedata, aes(x=Ray, y=mean, colour=groupvar,group=groupvar)) + 
    geom_errorbar(aes(ymin=mean-se, ymax=mean+se), width=.1,position=pd) +
    geom_line(position=pd) +
    geom_point(position=pd)+
    ylab("Ray Value") +
    xlab("Ray type")+
    scale_colour_hue(name="Group type", 
                     breaks=c("(0,0.2]", "(0.2,1]"))

我的照片如下: enter image description here