rggplot2lmabline

Add abline in ggplot2 which data from lm() result failed


I want to add abline() to the scatter plot , blow code only can return the scatter plot (the abline can't show). Anyone can help on this ? Thanks!

library(tidyverse)
model <- lm(mpg~ disp,data=mtcars)

abline_data <- data.frame(intercept=coef(model)[1],
                                 slope=coef(model)[2])

mtcars %>%  ggplot(aes(x=mpg,y=disp))+
  geom_point()+
  geom_abline(data=abline_data,aes(intercept=coef(model)[1] ,slope=coef(model)[2]),
              color="red",size =6)

Solution

  • Switch your independent/dependent variables in the ggplot(aes()) call to match the function (mpg as dependent on y-axis, disp as independent on x-axis):

    library(tidyverse)
    model <- lm(mpg~ disp,data=mtcars)
    
    abline_data <- data.frame(intercept=coef(model)[1],
                              slope=coef(model)[2])
    
    mtcars %>%  ggplot(aes(x=disp,y=mpg))+
      geom_point()+
      geom_abline(data=abline_data,
                  aes(intercept=intercept,
                      slope=slope),
                  color="red",size =6)