stat_smooth中的行为不同lm

时间:2015-08-03 15:02:47

标签: r ggplot2 lm

this问题中有人询问是否可以根据线性回归线更改ggplot2图中的颜色。

建议的解决方案有效,点在图的上方和下方有不同的颜色。

library(ggplot2)

set.seed(2015)
df <-  data.frame(x = rnorm(100),
                  y = rnorm(100))


# Fit linear regression
l = lm(y ~ x, data = df)

# Make new group variable based on residuals
df$group = NA
df$group[which(l$residuals >= 0)] = "above"
df$group[which(l$residuals < 0)] = "below"

# Make the plot
ggplot(df, aes(x,y)) +
  geom_point(aes(colour = group)) +
  geom_smooth(method = "lm", formula = y ~ x)

Expected output

但我想对y-1进行回归。正如this问题所述。

# Fit linear regression
l = lm(y - 1 ~ x, data = df)

# Make new group variable based on residuals
df$group = NA
df$group[which(l$residuals >= 0)] = "above"
df$group[which(l$residuals < 0)] = "below"

# Make the plot
ggplot(df, aes(x,y)) +
  geom_point(aes(colour = group)) +
  geom_smooth(method = "lm", formula = y - 1 ~ x)

enter image description here

这不是我的预期。我认为stat_smooth做了预期的事情。然而,lmy ~ xy - 1 ~ x

提供了相同的结果

我在这里缺少什么?

1 个答案:

答案 0 :(得分:2)

如果您想根据线条的位置对点进行着色,您可以尝试将实际值与预测值进行比较,而不是使用残差

df$group = NA
df$group[df$y>predict(l)] = "above"
df$group[df$y<predict(l)] = "below"