Patrick Glettig
Patrick Glettig

Reputation: 601

Ggplot: 1 Regression line with constant and 1 without

For a university exercise, I would like to plot two regression lines in the same graph: one regression includes a constant, the other one doesn't. It should illustrate how removing the constant changes the regression line.

However, when I use the following ggplot-command, I only get one regression line. Does anybody know the reason for this and how to fix it?

data(mtcars)
ggplot(mtcars, aes(x=disp, y=mpg)) +
  geom_point() +    # Scatters
  geom_smooth(method=lm, se=FALSE)+
  geom_smooth(method=lm, aes(color='red'),
              formula = y ~ x -0, #remove constant
              se=FALSE)

I tried this, but it doesn't do the trick.

Upvotes: 0

Views: 660

Answers (2)

captbullett
captbullett

Reputation: 11

good day,

the good book said to do it like this: http://bighow.org/questions/18280770/formatting-regression-line-equation-using-ggplot2-in-r I cant take credit for the code writing but the research ...

Have a great day... captbullett

Upvotes: 0

duckmayr
duckmayr

Reputation: 16920

You almost got it; to remove the intercept, you need + 0 or - 1, but not - 0; from help("lm"):

A formula has an implied intercept term. To remove this use either y ~ x - 1 or y ~ 0 + x. See formula for more details of allowed formulae.

So, we can do this:

library(ggplot2)

data(mtcars)
ggplot(mtcars, aes(x=disp, y=mpg)) +
    geom_point() +    # Scatters
    geom_smooth(method=lm, se=FALSE)+
    geom_smooth(method=lm, aes(color='red'),
                formula = y ~ x - 1, #remove constant
                se=FALSE)

Created on 2018-10-07 by the reprex package (v0.2.1)

Upvotes: 3

Related Questions