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

Customize ggplot so geom_abline layer appears only for a specific range along the x axis

Here I’m creating a linear model and putting the coefficients for that model in a graph.

model <- lm(mpg ~ wt, mtcars)

ggplot(mtcars, aes(x = wt, y = mpg)) +
  geom_point() + 
  geom_abline(intercept = coefficients(model)[1], slope = coefficients(model)[2])

enter image description here

How could I make it so this line only extends between a custom range along the x-axis? If I wanted the line to only appear between the ranges of wt = 2 and wt = 4, for instance? Geom_abline I think just runs forever.

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

>Solution :

predict() y values for your desired range limits, then use those values with geom_line():

library(ggplot2)

trendline <- data.frame(wt = c(2, 4)) 
trendline$mpg <- predict(model, newdata =
trendline)

ggplot(mtcars, aes(x = wt, y = mpg)) +
  geom_point() + 
  geom_line(data = trendline)

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