Currently, the below code (part of a more comprehensive code) generates a line that ranges from the very left to the very right of the graph.
geom_abline(intercept=-8.3, slope=1/1.415, col = "black", size = 1,
lty="longdash", lwd=1) +
However, I would like the line to only range from x=1 to x=9; the limits of the x-axis are 1-9.
In ggplot2, is there a command to reduce a line that is derived from a manually defined intercept and slope to only cover the range of the x-axis value limits?
You could use geom_segment
instead of geom_abline
if you want to manually define the line. If your slope is derived from the dataset you are plotting from, the easiest thing to do is use stat_smooth
with method = "lm"
.
Here is an example with some toy data:
set.seed(16)
x = runif(100, 1, 9)
y = -8.3 + (1/1.415)*x + rnorm(100)
dat = data.frame(x, y)
Estimate intercept and slope:
coef(lm(y~x))
(Intercept) x
-8.3218990 0.7036189
First make the plot with geom_abline
for comparison:
ggplot(dat, aes(x, y)) +
geom_point() +
geom_abline(intercept = -8.32, slope = 0.704) +
xlim(1, 9)
Using geom_segment
instead, have to define the start and end of the line for both x
and y
. Make sure line is truncated between 1 and 9 on the x axis.
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)
Using stat_smooth
. This will draw the line only within the range of the explanatory variable by default.
ggplot(dat, aes(x, y)) +
geom_point() +
stat_smooth(method = "lm", se = FALSE, color = "black") +
xlim(1, 9)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With