rggplot2linear-regressionquadratic

Draw separate linear and quadratic regression graphs for each group in the same panel


I'd like to draw linear and quadratic regression line per group (data is different).

For example, I make a graph like below.

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))+
  
  stat_smooth(aes(group=group, color=group), 
              method='lm', linetype=1, se=FALSE, 
              formula=y~x, linewidth=0.5) +
  
  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)

Then, I think group A is better to show quadratic regression. In this case, how can I draw two independent regression graph (Group A: quadratic, Group B: linear)?

Always many thanks,

enter image description here


Solution

  • One way is to use two geom_smooth() and filter dataA by group:

    library(dplyr)
    library(ggplot2)
    
    dataA %>% 
      ggplot(aes(x, y)) + 
      geom_point(aes(color = group)) + 
      geom_smooth(data = filter(dataA, group == "A"), 
                  method = "lm", 
                  formula = y ~ x + I(x^2), 
                  aes(color = group), 
                  se = FALSE) + 
      geom_smooth(data = filter(dataA, group == "B"), 
                  method = "lm", 
                  aes(color = group), 
                  se = FALSE) +
      theme_bw()
    

    Result:

    enter image description here