如何在散点图中绘制直线交叉数据中心?

How to draw straight line cross center of data in scatter plot?

我想用 ggplot 绘制一个散点图,geom_smooth() 以 45 度角穿过我的数据的中心不会自动绘制。

正如这里显示的那样,geom_smooth() 有小的倾斜,我改变了不同的方法 lm、auto 等,但没有区别。

geom_smooth(color = "black", alpha = 0.5, method = "lm", se = F)

如何画线正好穿过粉色圆点的中间?

geom_smooth(aes(group = type))

这将为每种类型提供不同的曲线。然后,如果需要,您可以弄清楚如何排除其他人

library(ggplot2)
n <- 300
x <- seq(0,100,,n)
type <- factor(c(0,1)[sample(1:2, n, replace = TRUE)])
y <- 4 + 2*x + rnorm(n, sd=10) - 10*as.numeric(type)
df <- data.frame(x=x, y=y, type=type)
plot(y~x, df, bg=c("blue", "pink")[df$type], pch=21)

bp <- ggplot(df, aes(x = x, y = y, col=type))
bp +
  geom_point() +
  geom_smooth(color = "black", alpha = 0.5, method = "lm", se = F) + 
  geom_smooth(aes(group = type), data = subset(df, type==0), se=F)

你想要这样的东西吗?

geom_abline(intercept = 0, slope = 1)

这将绘制一条通过 0 的 45º 角的线。

我认为 geom_smooth 正在计算所有点的回归。尝试删除所有 color 参数以获得平滑的分组。您可以查看不同的地块

a <- data.frame(x = c(1:10,2:11),y = c(2:11,1:10), label = c(rep("a",10),rep("b",10)))

ggplot(a, aes(x,y)) + geom_point(aes(color = label)) + geom_smooth(aes(color = label))
ggplot(a, aes(x,y)) + geom_point(aes(color = label)) + geom_smooth(color="black")