How to prevent the spread of the line across the schedule

Currently, the code below (part of a more complete code) generates a line that ranges from the leftmost to the rightmost chart.

geom_abline(intercept=-8.3, slope=1/1.415, col = "black", size = 1,
          lty="longdash", lwd=1) +

However, I would like the line to be only from x = 1 to x = 9; x-axis limits are 1-9.

Is there a command in ggplot2 to reduce the string obtained from a manually set intercept and tilt to cover only the range of values ​​along the x axis?

+4
source share
1 answer

geom_segment geom_abline, . , , stat_smooth method = "lm".

:

set.seed(16)
x = runif(100, 1, 9)
y = -8.3 + (1/1.415)*x + rnorm(100)

dat = data.frame(x, y)

:

coef(lm(y~x))

(Intercept)           x 
 -8.3218990   0.7036189 

geom_abline :

ggplot(dat, aes(x, y)) +
    geom_point() +
    geom_abline(intercept = -8.32, slope = 0.704) +
    xlim(1, 9)

geom_segment , x, y. , 1 9 x.

ggplot(dat, aes(x, y)) +
    geom_point() +
    geom_segment(aes(x = 1, xend = 9, y = -8.32 + .704, yend = -8.32 + .704*9)) +
    xlim(1, 9)

stat_smooth. .

ggplot(dat, aes(x, y)) +
    geom_point() +
    stat_smooth(method = "lm", se = FALSE, color = "black") +
    xlim(1, 9)
+1

All Articles