尽管使用ggplot2进行了两组测试,但具有单个回归线的散点图 [英] Scatterplot with single regression line despite two groups using ggplot2

查看:51
本文介绍了尽管使用ggplot2进行了两组测试,但具有单个回归线的散点图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用ggplot2生成散点图,它既包含所有数据点的回归线(无论它们来自哪个组),但同时通过分组变量来改变标记的形状.下面的代码产生了组标记,但是带有两条回归线,每组一条.

I would like to produce a scatter plot with ggplot2, which contains both a regression line through all data points (regardless which group they are from), but at the same time varies the shape of the markers by the grouping variable. The code below produces the group markers, but comes up with TWO regression lines, one for each group.

#model=lm(df, ParamY~ParamX)
p1<-ggplot(df,aes(x=ParamX,y=ParamY,shape=group)) + geom_point() + stat_smooth(method=lm)

我该如何编程?

推荐答案

您不必在geom_point中重做完整的aes并添加另一层,只需将形状aes移动到致电:

you shouldn't have to redo your full aes in the geom_point and add another layer, just move the shape aes to the geom_point call:

df <- data.frame(x=1:10,y=1:100+5,grouping = c(rep("a",10),rep("b",10)))
ggplot(df,aes(x=x,y=y)) + 
geom_point(aes(shape=grouping)) + 
stat_smooth(method=lm)

为了帮助您发表评论:

因为对于我而言,annotate最终都可以在每个方面使用相同的标签.我喜欢制作一个迷你的data.frame,它具有用于刻面和刻面级别的变量,并带有另一列代表我要使用的标签的列.在这种情况下,标签数据帧称为dfalbs.

because annotate can end up, for me anyway, with the same labels on each facet. I like to make a mini data.frame that has my variable for faceting and the facet levels with another column representing the labels I want to use. In this case the label data frame is called dfalbs.

然后使用它来标记数据框以分别标记构面,例如

Then use this to label data frame to label the facets individually e.g.

df <- data.frame(x=1:10,y=1:10,grouping =   
                  c(rep("a",5),rep("b",5)),faceting=c(rep(c("oneR2","twoR2"),5)))


dflabs <- data.frame(faceting=c("oneR2","twoR2"),posx=c(7.5,7.5),posy=c(2.5,2.5))

ggplot(df,aes(x=x,y=y,group=faceting)) + 
       geom_point(aes(shape=grouping),size=5) + 
       stat_smooth(method=lm) +
       facet_wrap( ~ faceting) +
       geom_text(data=dflabs,aes(x=posx,y=posy,label=faceting))

这篇关于尽管使用ggplot2进行了两组测试,但具有单个回归线的散点图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆