在ggplot2中的同一图形上绘制两个不同的数据帧 [英] Plotting two different data frames on same figure in ggplot2
本文介绍了在ggplot2中的同一图形上绘制两个不同的数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图在彼此的上方绘制两个不同的图形.根据完整的数据集构建一个图形,并将其绘制为y与某些分类变量x的关系.第二个数据帧只是每个分类x值的均值y的两个值,以及相关的标准误差.我可以独立创建两个图,但是我想在另一个图上重叠.我怎样才能做到这一点?我已经复制了代码以生成数据,并在此处希望彼此重叠的绘图的代码.
I am trying to plot two different figures on top of eachother. One figure is built from the full data set, and is plotted as y vs. some categorical variable x. The second data frame is just two values for the means of each categorical x-value in terms of y, and associated standard errors. I can create both plots independently, but I would like to overlap one on top of the other. How can I do this? I have copied code to generate the data, and code for the plots that I wish to overlay on each other here.
#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)
推荐答案
如何解决
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
)
这篇关于在ggplot2中的同一图形上绘制两个不同的数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文