Search code examples
rggplot2graphscatter-plottrendline

Multiple trendlines for factors ggplot2 and colors


I'm not too familiar with ggplot but it looks better than what I've been getting with plot_ly I'm having trouble getting a trendline for each factor of the series. The trendlines just don't show up in the generated graph

Here is the code I've been working with

ggplot(subset(df,FACTOR %in% c("1","2")), aes(x= DUR, y= TEMP, color=FACTOR)) +
geom_point() +
geom_smooth(data=subset(df, FACTOR=="1"), method=lm , se=FALSE) +
geom_smooth(data=subset(df, FACTOR=="2"), method=lm , se=FALSE) +
xlab("Duration (min)") +
ylab('Change in Temperature (C)')

My df looks like this

DUR    TEMP    FACTOR
#      #        1
#      #        1
#      #        2
#      #        3
#      #        4
...   ...      ...

Thanks


Solution

  • try to add the factor as group in the aes statement and for drawing with one geom_smooth call all you need (not sure if method should be "lm" instead of only lm):

    library(ggplot2)
    
    ggplot(subset(df,GROUP %in% c("1","2")), aes(x= DUR, y= TEMP, color=FACTOR, group = FACTOR)) +
    geom_point() +
    geom_smooth(method=lm , se=FALSE) +
    xlab("Duration (min)") +
    ylab('Change in Temperature (C)')
    

    Not sure why you filter bey "GROUP" in subset - should be FACTOR from what I understand of your code and data snipped