如何在同一面板为不同组分别绘制线性与二次回归曲线?
解决方案
要实现A组二次回归、B组线性回归在同一面板展示,你可以拆分stat_smooth图层,分别为两组指定不同的回归公式,具体修改后的代码如下:
x=rep(c(0,40,80,120,160),time=2) y=c(16,21,22,26,35,29,44,72,61,54) group=rep(c("B","A"),each=5) dataA=data.frame(x,y,group) ggplot(data=dataA, aes(x=x, y=y))+ # B组线性回归 stat_smooth(aes(color=group), method='lm', linetype=1, se=FALSE, formula=y~x, linewidth=0.5, subset=group=="B") + # A组二次回归 stat_smooth(aes(color=group), method='lm', linetype=1, se=FALSE, formula=y~poly(x, 2, raw=TRUE), linewidth=0.5, subset=group=="A") + geom_point(aes(fill=group, shape=group), color="black", size=4) + scale_color_manual(values=c("Dark red","grey15"))+ scale_fill_manual(values=c("Dark red","grey15"))+ scale_shape_manual(values=c(24,25))+ scale_x_continuous(breaks=seq(0,160,40), limits = c(0,160)) + scale_y_continuous(breaks=seq(0,80,20), limits = c(0,80)) + theme_classic(base_size=20, base_family="serif")+ theme(legend.position=c(0.89,0.08), legend.title=element_blank(), legend.key=element_rect(color=alpha("grey",.05), fill=alpha("grey",.05)), legend.background= element_rect(fill=alpha("grey",.05)), strip.background = element_rect(color="white", linewidth=0.5,linetype="solid"), axis.line=element_line(linewidth=0.5, colour="black"))+ windows(width=5.5, height=5)
关键修改说明
- 替换了原来单一组的
stat_smooth,新增两个独立的回归图层:- 针对B组:用
subset=group=="B"筛选数据,公式y~x对应线性回归 - 针对A组:用
subset=group=="A"筛选数据,公式y~poly(x, 2, raw=TRUE)对应二次回归(raw=TRUE确保使用原始的二次项计算,若不需要可省略该参数,默认会生成正交多项式)
- 针对B组:用
- 两个
stat_smooth都保留了color=group的映射,确保回归曲线颜色与对应组的点颜色一致,和原代码的配色设置保持统一
内容的提问来源于stack exchange,提问作者J.K Kim
相关产品推荐
相关产品推荐

