在ggplot2中的同一图上绘制两个不同的数据帧

时间:2014-11-18 20:37:48

标签: r ggplot2

我试图在彼此之上绘制两个不同的数字。一个数字是从完整数据集构建的,并绘制为y与某些分类变量x。第二个数据帧只是y的每个分类x值的均值的两个值,以及相关的标准误差。我可以独立创建两个图,但我想在另一个上面重叠。我怎样才能做到这一点?我已经复制了代码来生成数据,以及我希望在这里相互叠加的图的代码。

#first create a data set, called 'data'
x<-c(1:100)
a<-rep(0,50)
b<-rep(1,50)
class<-c(a,b)
y<-x*2 + class*20 + rnorm(100,0,3)
data<-data.frame(x,class,y)

#then summarize the means and standard errors of that data by the grouping 'class', using     the meanerr function I have scripted here
meanerr<- function(data,param,grouping){
    means<-aggregate(param~grouping,data=data,FUN=mean)
    sd<-aggregate(param~grouping,data=data,FUN=sd)
    count<-aggregate(param~grouping,data=data,FUN=length)
    err<-sd$param/sqrt(count$param)
    output<-cbind(means,err)
    return(output)
}

means<- meanerr(data,y,class)


#plot 1- all the points by class
ggplot(data,aes(x=class,y=y))+geom_jitter(alpha=0.2,position=position_jitter(width=.1))

#plot 2- the means and standard errors by class
ggplot(means,aes(x=grouping,y=param))+geom_point()+geom_errorbar(aes(ymin=param-err,ymax=param+err),width=0.1)

1 个答案:

答案 0 :(得分:2)

这个怎么样

ggplot()+geom_errorbar(data=means,aes(x=factor(grouping),ymax=param+err,ymin=param-err),width=.2) 
+geom_point(data=data,aes(x=factor(class),y=y),position='jitter',alpha=.4)

enter image description here