Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading