ggplot2绘图stat_smooth按变量分组

时间:2014-05-10 12:59:09

标签: r plot ggplot2 gam

> head(d)
  TargetGroup2012 TargetGroup2000     bmi3 age3 PA_Score education3 asthma3 allasthma3 tres3
1               2               2 20.89796   55        2          2       0          0     0
2               2               2 20.20038   49        3          2       0          0     0
3               2               2 30.47797   58        3          1       0          0     0
4               2               2 34.13111   51        2          2       0          0     0
5               3               2 23.24380   52        3          1       0          0     0
6               3               2 16.76574   62        2          3       0          0     0
  wheeze3 SmokingGroup_Kai
1       0                4
2       1                4
3       0                5
4       1                4
5       0                3
6       0                3

我正在使用:

进行gam绘图
MyFormula=asthma3~s(bmi3)+s(age3)+PA_Score+eucation3
c <- ggplot()
c + stat_smooth(data=d,aes(bmi3,asthma3),method="gam",formula=MyFormula,color="red")+
stat_smooth(data=d3,aes(b3,as3),fomula=as3~s(b3))+xlab("BMI3")+ylab("Asthma3")

我希望根据变量TargetGroup2012的值在同一个图上有不同的行。

我可以做到这一点:

d1=d[d$TargetGroup2012==1,]  
d2=d[d$....]
And then plot...

有更快的方法吗?也许使用像groupby这样的东西?

编辑: 正确的解决方案

d=data[,c("TargetGroup2012","TargetGroup2000","bmi3","age3","PA_Score","education3","asthma3","allasthma3","tres3","wheeze3","SmokingGroup_Kai")]
d$TargetGroup2012=factor(d$TargetGroup2012)

d=na.exclude(d)

ggplot() + stat_smooth(data=d,aes(x=bmi3,y=asthma3,group=TargetGroup2012,color=TargetGroup2012),method="gam",fomula=asthma3~s(bmi3)+s(age3)+PA_Score+SmokingGroup_Kai)+  xlab("BMI3")+ylab("Asthma3")

1 个答案:

答案 0 :(得分:1)

要获得不同颜色的线条,您可以在color=TargetGroup2012功能中使用stat_smooth。这应该会给你想要的结果。