如何在 ggplot2 中将趋势线添加到部分数据?

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

我有这样的数据和情节,

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)

有没有办法让趋势线仅应用于 x 大于特定数字(例如 3)的值?

你可以这样做:

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

您只能将当前的 aes 应用到 geom_point,并创建一个新列(即我的代码中的 x2)以映射到 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)

reprex package (v2.0.1)

于 2022-05-07 创建

与上述两者类似,仅使用 subset:

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