您如何将趋势线添加到GGPLOT2中的一部分数据中?

发布于 2025-01-27 03:51:37 字数 402 浏览 3 评论 0原文

我有数据和这样的图,

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的值大于x一个数字,例如3?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

ゃ懵逼小萝莉 2025-02-03 03:51:37

您可以做到这一点:

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

“

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

哀由 2025-02-03 03:51:37

您只能将当前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软件包(v2.0.1)

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)

云淡风轻 2025-02-03 03:51:37

与上述两者相似,仅使用subset

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

”在此处输入图像描述”

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文