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.
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
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))