Adding Straight Lines to a Plot in R Programming – abline() Function

abline() Function in detail

The abline() function in R is used to add one or more straight lines to a graph. It can be used to add vertical, horizontal, or regression lines to a plot.

Syntax:

abline(a=NULL, b=NULL, h=NULL, v=NULL, ...)

Parameters:

  • a, b: Specifies the intercept and the slope of the line.
  • h: Specifies y-value(s) for horizontal line(s).
  • v: Specifies x-value(s) for vertical line(s).

Returns:

A straight line in the plot.

Example 1: Adding a Vertical Line to the Plot

# Create scatter plot
plot(pressure)

# Add vertical line at x = 200
abline(v = 200, col = "blue")

Output:

Example 2: Adding a Horizontal Line to the Plot

# Create scatter plot
plot(pressure)

# Add horizontal line at y = 300
abline(h = 300, col = "red")

Output:

Example 3: Adding a Regression Line

par(mgp = c(2, 1, 0), mar = c(3, 3, 1, 1))

# Fit regression line
reg <- lm(pressure ~ temperature, data = pressure)
coeff = coefficients(reg)

# Equation of the line
eq = paste0("y = ", round(coeff[1], 1), " + ", round(coeff[2], 1), "*x")

# Plot
plot(pressure, main = eq)
abline(reg, col = "darkgreen")

Output:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *