Search code examples
rggplot2trendline

Trying to add a loess smooth line to ggplot while retaining colored groupings


I'm hoping to create a scatterplot with a loess smooth line to capture the trend across the full time period. At the same time, the study population is pregnent, so I'm wanting to color each point according to which gestational stage the participants are in to see if the trendline fluctuates according to gestational age.The code for the last image, in which I've combined the two concepts, is below. I'm fairly new to R, sorry if the code is messy or the question is unclear!

Loess

Colored Groups

Colors and too many loess

scr_delivery_plot<- ggplot(sbk2, aes(x = as.numeric(gestational_age), y = as.numeric(scr), color = as.factor(status))) +
  geom_point()+
  scale_color_manual(values = cols)

delscrplt2<- scr_delivery_plot + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) 

print(delscrplt2+ ggtitle("Scr: +/- 14 day delivery definition")
      + labs(colour = "Trimesters+Delivery")) +
  geom_smooth(method = "loess")


Solution

  • There are various ways to do this. Depends as to how your plot is structured. I would recommend setting the color aesthetic to NULL.

    ggplot(sbk2, aes(x = as.numeric(gestational_age), y = as.numeric(scr), color = as.factor(status))) +
      geom_point() +
      scale_color_manual(values = cols)+
      theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) + 
      ggtitle("Scr: +/- 14 day delivery definition") +
      labs(colour = "Trimesters+Delivery") +
      geom_smooth(aes(color = NULL), # THIS IS THE ADDITION
                     method = "loess")
    

    ...

    OR if the color aesthetic is needed once, then set it within the points...

    ggplot(sbk2, aes(x = as.numeric(gestational_age), y = as.numeric(scr))) +
      geom_point(aes(color = as.factor(status))) + # check addition
      geom_smooth(method = "loess") + 
      scale_color_manual(values = cols) +
      theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) + 
      labs(title = "Scr: +/- 14 day delivery definition",
           colour = "Trimesters+Delivery") 
    

    Example using iris dataset:

    iris %>%
      ggplot(aes(Sepal.Length, Petal.Length)) +
      geom_point(aes(color = Species))+ 
      geom_smooth()
    

    enter image description here