Home > Net >  How do you add trendline to part of data in ggplot2?
How do you add trendline to part of data in ggplot2?

Time:05-08

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?

CodePudding user response:

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

CodePudding user response:

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 enter image description here

  • Related