The function abline()
Syntax of abline()
abline(a = NULL, b = NULL, h = NULL, v = NULL, reg = NULL, coef = NULL, col = NULL, lty = NULL, lwd = NULL, ...)
- a: Intercept of the line (for y = a + bx).
- b: Slope of the line (for y = a + bx).
- h: Numeric value(s) for horizontal lines (y = h).
- v: Numeric value(s) for vertical lines (x = v).
- reg: A regression object (e.g., from lm()).
- coef: Coefficients of a line (a and b).
- col: Color of the line.
- lty: Line type (e.g., 1 for solid, 2 for dashed).
- lwd: Line width.
- …: Additional graphical parameters.
Examples
Adding a Horizontal Line
x <- 1:10 y <- x^2 plot(x, y, main = "Plot with Horizontal Line", xlab = "X", ylab = "Y") abline(h = 50, col = "blue", lty = 2, lwd = 2)
- h = 50: Adds a horizontal line at y = 50.
- col = “blue”: Line color.
- lty = 2: Dashed line.
- lwd = 2: Line width.
Adding a Vertical Line
plot(x, y, main = "Plot with Vertical Line", xlab = "X", ylab = "Y") abline(v = 5, col = "red", lty = 3, lwd = 2)
- v = 5: Adds a vertical line at x = 5.
- col = “red”: Line color.
- lty = 3: Dotted line.
- lwd = 2: Line width.
Adding a Line with Slope and Intercept
plot(x, y, main = "Plot with Line by Slope and Intercept", xlab = "X", ylab = "Y") abline(a = 10, b = 1, col = "green", lty = 1, lwd = 2)
- a = 10: y-intercept.
- b = 1: Slope of the line.
- col = “green”: Line color.
- lty = 1: Solid line.
- lwd = 2: Line width.
Adding a Regression Line
model <- lm(y ~ x) plot(x, y, main = "Plot with Regression Line", xlab = "X", ylab = "Y") abline(model, col = "purple", lty = 1, lwd = 2)
- model: Linear model object.
- abline(model): Adds the regression line from the model.
- col = “purple”: Line color.
- lty = 1: Solid line.
- lwd = 2: Line width.
Adding Multiple Lines
plot(x, y, main = "Plot with Multiple Lines", xlab = "X", ylab = "Y") abline(h = c(20, 60), col = c("blue", "red"), lty = c(2, 3), lwd = 2)
- h = c(20, 60): Adds two horizontal lines.
- col = c(“blue”, “red”): Colors for each line.
- lty = c(2, 3): Line types for each line.
- lwd = 2: Line width for both lines.
Notes
- abline() works best with simple linear functions. For more complex lines or shapes, consider using lines() or curve().
- Customization: You can combine abline() with other functions (like points() or text()) for more complex plots.
Post Views: 75