Kayla
Kayla

Reputation: 59

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?

Upvotes: 1

Views: 2762

Answers (3)

langtang
langtang

Reputation: 24722

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

Upvotes: 4

TarJae
TarJae

Reputation: 78927

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

Upvotes: 1

benson23
benson23

Reputation: 19097

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)

Upvotes: 2

Related Questions