user3122822
user3122822

Reputation: 127

Different colours in ggplot based on geom_smooth

I created a ggplot with linear geom_smooth now i would like to have the points, from the geom_point to have a different colour below and above the linear smooth line.

I know I can add the color to the point by doing geom_point(aes(x, y, colour = z)). My problem is how to determine if a point in the plot is below or above the linear line.

Can ggplot2 do this or do have to create a new column in the data frame first?

Below is the sample code with geom_smooth but without the different colours above and below the line.

Any help is appreciated.

library(ggplot2)

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

ggplot(df, aes(x,y)) +
 geom_point() +
 geom_smooth(method = "lm")

Upvotes: 1

Views: 1916

Answers (1)

hugot
hugot

Reputation: 981

I believe ggplot2 can't do this for you. As you say, you could create a new variable in df to make the colouring. You can do so, based on the residuals of the 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 the plot
ggplot(df, aes(x,y)) +
  geom_point(aes(colour = group)) +
  geom_smooth(method = "lm")

Note that the colour argument has to be passed to geom_point(), otherwise geom_smooth() will produce a fit to each group separately.

Result:

example_regression

Upvotes: 4

Related Questions