'How do you add trendline to part of data in ggplot2?

I have data and a plot like this,

x = c(1,2,3,4,5,6,7,8,9,10,11,12)
y1 = x^2-5
y2 = -x^2+1

data <- data.frame(x,y1,y2)
data1 = data.frame(pivot_longer(data,2:3))

ggplot(data1, aes(x, y = value, color = name))+ 
  geom_point()+
  geom_smooth(method = 'lm',se = FALSE)

Output

Is there a way to have the trendline only applying to values for x greater than a certain number, like 3?



Solution 1:[1]

Similar to both above just using subset:

ggplot(data1, aes(x, y = value, color = name))+ 
  geom_point()+
  geom_smooth(data=subset(data1, x > 3), method = 'lm',se = FALSE)

enter image description here

Solution 2:[2]

You can do this:

ggplot(data1, aes(x, y = value, color = name))+ 
  geom_point()+
  geom_smooth(data=dplyr::filter(data1,x>3), method = 'lm',se = FALSE)

g3

Solution 3:[3]

You can apply the current aes to geom_point only, and create a new column (i.e. x2 in my code) for mapping to geom_smooth.

library(tidyverse)
x = c(1,2,3,4,5,6,7,8,9,10,11,12)
y1 = x^2-5
y2 = -x^2+1

data <- data.frame(x,y1,y2)
data1 = data.frame(pivot_longer(data,2:3))

data1 %>% mutate(x2 = ifelse(x > 3, x, NA)) %>% 
  ggplot()+ 
  geom_point(aes(x, y = value, color = name)) +
  geom_smooth(aes(x2, y = value, color = name), method = 'lm',se = FALSE)

Created on 2022-05-07 by the reprex package (v2.0.1)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 TarJae
Solution 2
Solution 3 benson23