# The abline() function in R

Do not miss this article if you are looking for a function to draw a straight line in R. Today, we will introduce the abline() function in R that helps you draw a straight line horizontally, vertically, and cross.

## The abline() function in R

The abline() function draws a straight horizontal, vertical, and cross line.

Syntax:

abline(a, b, h, v)

Parameters:

• a: The intercept if the line is in cross
• b: The slope if the line is in cross
• h: Horizontal value
• v: Vertical value

## Some examples of the abline() function

### Draw the horizontal line

Our previous article showed you how to use the dnorm() function and draw the random variables x and their probability density values. Now, we will draw a horizontal line to mark the mean value of probability density.

Code:

# Create a vector x having balance values around 0
x <- seq(-5, 5, by = 0.001)

# Calculate the probability density of the vector x
y <- dnorm(x)

# Calculate the mean value of probability density
y_mean <- mean(y)

# Visualize vector x and its probability density values
plot(x, y)

# Draw the horizontal line to mark the mean value of probability density
abline(h = y_mean, col = "red")

Result:

### Draw the vertical line

Random variables x are balanced around x. We can draw a vertical line to mark the median value of x, and of course, the value is zero.

Code:

# Create a vector x having balance values around 0
x <- seq(-5, 5, by = 0.001)

# Calculate the probability density of the vector x
y <- dnorm(x)

# Calculate the mean value of probability density
y_mean <- mean(y)

# Visualize vector x and its probability density values
plot(x, y)

# Draw the vertical line to mark the median value of x
abline(v = 0, col = "red")

Result:

### Draw the cross line

In this example, we will draw a cross line representing the relation of features x and y of a linear regression model. First, we generate 40 values for feature x, then create random bias values from -3 to 3. After that, we create values for y by multiplying the feature x with a defined slope equal to 2 then, plus the bias. We can easily calculate the suitable slope and intercept for x and y by the lm() function. Finally, we visualize the relation by plotting x and y and drawing the cross line representing the linear regression model.

Code:

set.seed(0)

# Generate 40 values for x
x <- seq(40, 100, length.out = 40)

# Create bias
bias <- runif(40, -3, 3)

# Create values for y from x and bias
y <- 2 * x + bias

# Calculate the relation between x and y
reg <- lm(y ~ x)

# Plot x and y
plot(x, y, main = "Linear regression")

# Draw the cross line
abline(reg)

Result:

## Summary

In summary, the abline() function can draw a straight line vertically, horizontally, and cross. It is helpful to represent the comparison and the relation of features when analyzing data.

Maybe you are interested:

Posted in R