如何在 ggplot2 R 中绘制一条回归线,但按不同因素绘制颜色点?

发布于 2025-01-19 17:26:22 字数 698 浏览 1 评论 0原文

散点图由因子z颜色编码。默认情况下,ggplot2还按因子盆栽回归线。我想绘制通过数据的单个回归线。我该如何实现?

x <- c(1:50)
y <- rnorm(50,4,1)
z <- rep(c("P1", "P2"), each  = 25)
df <- data.frame(x,y,z)

my.formula = y ~ x
ggplot(aes(x = x, y = y, color = z), data = df) +
  geom_point() + scale_fill_manual(values=c("purple", "blue")) +
  geom_smooth(method="lm", formula = y ~ x ) + 
  stat_poly_eq(formula = my.formula, aes(label = paste(..eq.label.., ..rr.label.., sep = "~~~")),  parse = TRUE, size = 2.5, col = "black")+
  theme_classic()

The scatterplot is colour-coded by factor z. By default, ggplot2 also pots the regression lines by factor. I want to plot a single regression line passing through the data. How do I achiece this?

x <- c(1:50)
y <- rnorm(50,4,1)
z <- rep(c("P1", "P2"), each  = 25)
df <- data.frame(x,y,z)

my.formula = y ~ x
ggplot(aes(x = x, y = y, color = z), data = df) +
  geom_point() + scale_fill_manual(values=c("purple", "blue")) +
  geom_smooth(method="lm", formula = y ~ x ) + 
  stat_poly_eq(formula = my.formula, aes(label = paste(..eq.label.., ..rr.label.., sep = "~~~")),  parse = TRUE, size = 2.5, col = "black")+
  theme_classic()

enter image description here

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

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

发布评论

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

评论(1

顾铮苏瑾 2025-01-26 17:26:22

如果我理解正确,您可以在 aes 中指定 group = 1 来仅绘制一条回归线。您可以使用以下代码:

library(tidyverse)
library(ggpmisc)
my.formula = y ~ x
ggplot(aes(x = x, y = y, color = z, group = 1), data = df) +
  geom_point() + scale_fill_manual(values=c("purple", "blue")) +
  geom_smooth(method="lm", formula = y ~ x ) + 
  stat_poly_eq(formula = my.formula, aes(label = paste(..eq.label.., ..rr.label.., sep = "~~~")),  parse = TRUE, size = 2.5, col = "black")+
  theme_classic()

输出:

在此处输入图像描述

If I undertand you correctly, you can assign group = 1 in the aes to plot just one regression line. You can use the following code:

library(tidyverse)
library(ggpmisc)
my.formula = y ~ x
ggplot(aes(x = x, y = y, color = z, group = 1), data = df) +
  geom_point() + scale_fill_manual(values=c("purple", "blue")) +
  geom_smooth(method="lm", formula = y ~ x ) + 
  stat_poly_eq(formula = my.formula, aes(label = paste(..eq.label.., ..rr.label.., sep = "~~~")),  parse = TRUE, size = 2.5, col = "black")+
  theme_classic()

Output:

enter image description here

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