lines() Function in detail
The lines() function in R is used to add lines of different types, colors, and widths to an existing plot.
Syntax:
lines(x, y, col, lwd, lty)
Parameters:
- x, y: Vectors of coordinates
- col: Color of the line
- lwd: Width of the line
- lty: Type of line
Adding Lines to a Plot using lines() Function
Example 1: Adding a Line to a Scatter Plot
This example demonstrates how to create a scatter plot and add a line to it.
# Creating coordinate vectors
x <- c(2.1, 4.2, 1.5, -2.8, 6.3,
3.1, 4.0, 2.8, 2.6, 2.2, 2.0, 2.8)
y <- c(3.2, 6.5, 2.8, -2.5, 10.5, 4.8,
5.9, 5.1, 3.9, 3.2, 3.4, 4.8)
# Plotting the scatter plot
plot(x, y, cex = 1, pch = 3, xlab = "X-axis",
ylab = "Y-axis", col = "black")
# Creating another set of coordinates for the line
x2 <- c(3.5, 1.0, -1.8, 0.2)
y2 <- c(4.0, 5.2, 3.0, 3.5)
# Adding a red line to the plot
lines(x2, y2, col = "red", lwd = 2, lty = 1)
Output:

Example 2: Connecting Points with lines()
This example shows how to plot a scatter plot and connect the points using lines().
# Creating coordinate vectors
x <- c(2.1, 4.2, 1.5, -2.8, 6.3, 3.1,
4.0, 2.8, 2.6, 2.2, 2.0, 2.8)
y <- c(3.2, 6.5, 2.8, -2.5, 10.5, 4.8,
5.9, 5.1, 3.9, 3.2, 3.4, 4.8)
# Plotting the scatter plot
plot(x, y, cex = 1, pch = 3, xlab = "X-axis",
ylab = "Y-axis", col = "black")
# Connecting points with a red line
lines(x, y, col = "red")
Output:

Example: Adding Lines to a Plot in R using lines()
# Create sample data
x <- seq(-5, 5, length.out = 10)
y <- x^3
# Create a plot of the data
plot(x, y, main = "Adding Lines to a Plot", col = "blue")
# Add a vertical line at x = 0
abline(v = 0, col = "green", lwd = 2)
# Add a horizontal line at y = 0
abline(h = 0, col = "purple", lwd = 2)
# Add a diagonal line with slope -2 and intercept 3
abline(a = 3, b = -2, col = "orange", lty = 2, lwd = 2)
# Add a custom line using lines() function
x2 <- seq(-5, 5, length.out = 10)
y2 <- -x2^2 + 4
lines(x2, y2, col = "red", lty = 2, lwd = 2)
Output:

Leave a Reply