r - Different colours in ggplot based on geom_smooth -
i created ggplot linear geom_smooth have points, geom_point have different colour below , above linear smooth line.
i know can add color point doing geom_point(aes(x, y, colour = z)). problem how determine if point in plot below or above linear line.
can ggplot2 or have create new column in data frame first?
below sample code geom_smooth without different colours above , below line.
any appreciated.
library(ggplot2) df <- data.frame(x = rnorm(100), y = rnorm(100)) ggplot(df, aes(x,y)) + geom_point() + geom_smooth(method = "lm")
i believe ggplot2 can't you. say, create new variable in df make colouring. can so, based on residuals of linear model.
for example:
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 plot ggplot(df, aes(x,y)) + geom_point(aes(colour = group)) + geom_smooth(method = "lm") note colour argument has passed geom_point(), otherwise geom_smooth() produce fit each group separately.
result:

Comments
Post a Comment