R abline() function - Add reference lines
The R abline() function is used to add straight reference lines to an existing plot.
It can draw horizontal lines, vertical lines, or slanted lines, and is often used to mark means, thresholds, or trend lines.
The syntax format of the abline() function is as follows:
abline(a = NULL, b = NULL, h = NULL, v = NULL,
col = "black", lty = 1, lwd = 1)
Parameter description:
a, bThe intercept and slope of the line, i.e., y = a + b*x.
hThe y value of the horizontal line.
vThe x value of the vertical line.
ltyLine type: 1=solid, 2=dashed, 3=dotted.
lwdLine width.
Example
# Scatter plot
x <- 1:20
y <- x * 3 + rnorm(20, 0, 5)
plot(x, y, main = "Data and Trend Line",
xlab = "X", ylab = "Y",
col = "blue", pch = 16)
# Add regression trend line
abline(lm(y ~ x), col = "red", lwd = 2)
# Add horizontal reference line (mean of y)
abline(h = mean(y), col = "green", lty = 2, lwd = 2)
# Add vertical reference line
abline(v = 10, col = "purple", lty = 3, lwd = 2)
# Legend
legend("topleft",
legend = c("Regression Line", "Mean", "x=10"),
col = c("red", "green", "purple"),
lty = c(1, 2, 3), lwd = 2)
x <- 1:20
y <- x * 3 + rnorm(20, 0, 5)
plot(x, y, main = "Data and Trend Line",
xlab = "X", ylab = "Y",
col = "blue", pch = 16)
# Add regression trend line
abline(lm(y ~ x), col = "red", lwd = 2)
# Add horizontal reference line (mean of y)
abline(h = mean(y), col = "green", lty = 2, lwd = 2)
# Add vertical reference line
abline(v = 10, col = "purple", lty = 3, lwd = 2)
# Legend
legend("topleft",
legend = c("Regression Line", "Mean", "x=10"),
col = c("red", "green", "purple"),
lty = c(1, 2, 3), lwd = 2)
Executing the above code will display a scatter plot containing a regression line, a mean line, and a vertical reference line.
Other Extensions
R Language Examples