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

