Insert regression model into ggplot2

library(tidyverse)

# Base R ----------------------------------------------


model<-lm(disp~mpg,data=mtcars)
plot(mtcars$mpg,mtcars$disp)
abline(model)


# Ggplot2 -----------------------------------------------------------------

mtcars %>% 
    ggplot(aes(mpg,disp))+
    geom_point()

Now my question is how to add model into ggplot2 directly. Because the geom_abline function is asking for intercept and stuff. Is there a direct method for doing it.

For this kind of questions, a quick search on stackoverflow is usually a great source of solutions. For example:

1 Like

You can use geom_smooth() with method = "lm". This will automatically add a regression line for y ~ x to the plot.

ggplot(mtcars, aes(mpg, disp)) +
  geom_point() +
  geom_smooth(method = "lm")
4 Likes

In order to remove the confidence interval you need to add se = FALSE, i.e.:

ggplot(mtcars, aes(mpg, disp)) +
  geom_point() +
  geom_smooth(method = "lm", se = FALSE)
2 Likes

@lbusett

Hi thanks for the reply.

so is this the only way of using a model directly into ggplot2.

# read dataset
df = mtcars

# create multiple linear model
lm_fit <- lm(mpg ~ cyl + hp, data=df)
summary(lm_fit)

# save predictions of the model in the new data frame 
# together with variable you want to plot against
predicted_df <- data.frame(mpg_pred = predict(lm_fit, df), hp=df$hp)

# this is the predicted line of multiple linear regression
ggplot(data = df, aes(x = mpg, y = hp)) + 
  geom_point(color='blue') +
  geom_line(color='red',data = predicted_df, aes(x=mpg_pred, y=hp))

I am not looking for the the geom_smooth option. I was thinking may be there is something to geom_abline that I don't know yet.

Please let me know if that's the optimal solution.

Hi. If you don't want to use geom_smooth, you could probably also retrieve the slope and intercept of the regression line from lm and feed those to geom_abline

1 Like

So this is the only method there is nothing similar to the case functions abline(model).

Okay then thanks for replying

There's not the same one-liner, no. But you could also fortify() the fitted model and then plot using that data, e.g.

# Create the model
fit <- lm(disp ~ mpg, data = mtcars)

# Create the base plot
ggplot(mtcars, aes(mpg, disp))+
  geom_point() +
# Add the line using the fortified fit data, plotting the x vs. the fitted values
  geom_line(data = fortify(fit), aes(x = mpg, y = .fitted))
3 Likes

thanks a lot for this elegent solution.