在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)
但我想对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)
这不是我的预期。我认为stat_smooth
做了预期的事情。然而,lm
为y ~ x
和y - 1 ~ x
我在这里缺少什么?
答案 0 :(得分:2)
如果您想根据线条的位置对点进行着色,您可以尝试将实际值与预测值进行比较,而不是使用残差
df$group = NA
df$group[df$y>predict(l)] = "above"
df$group[df$y<predict(l)] = "below"