Open In App

Addition of Lines to a Plot in R Programming – lines() Function

Last Updated : 17 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In R, the lines() function is called to add on top of already existing plot. This is particularly helpful when you want to add more lines, such as trend lines, regression lines, or special lines, on a plot. The lines() function allows flexibility in line color, line width, and line type, with multiple choices for customizing your plot.

Syntax:

lines(x, y, col, lwd, lty)

Parameters: 

  • x, y: Vector of coordinates
  • col: Color of line
  • lwd: Width of line
  • lty: Type of line

Sample Scatter plot for demonstration

Here we are going to create a scatter plot using the dataset.

R
# Creating coordinate vectors
x <- c(1.3, 3.5, 1.4, -3.1, 5.7, 2.4,
       3.3, 2.5, 2.3, 1.9, 1.8, 2.3)
y <- c(2.5, 5.8, 2.1, -3, 12, 5, 6.2,
       4.8, 4.2, 3.5, 3.7, 5.2)

# Plotting the graph
plot(x, y, cex = 1, pch = 3, 
     xlab ="x", ylab ="y",
     col ="black")

Output:

sample-scatter-plot

Example 1: Adding a Line to a Scatter Plot

We will here begin by generating a scatter plot and then adding points connected with lines using the function lines().

R
x <- c(1.3, 3.5, 1.4, -3.1, 5.7,
       2.4, 3.3, 2.5, 2.3, 1.9, 1.8, 2.3)
y <- c(2.5, 5.8, 2.1, -3, 12, 5,
       6.2, 4.8, 4.2, 3.5, 3.7, 5.2)

# Plotting the graph
plot(x, y, cex = 1, pch = 3, xlab ="x",
     ylab ="y", col ="black")

x2 <- c(4.3, 1.2, -2.5, -0.4)
y2 <- c(3.5, 4.6, 2.5, 3.2)

# Plotting a line
lines(x2, y2, col = "red", 
      lwd = 2, lty = 1)

Output:

scatter-plot-r

Example 2: Using lines() to Connect Points in a Scatter Plot

Here we will make a scatter plot and then we will draw lines with lines() function

R
x <- c(1.3, 3.5, 1.4, -3.1, 5.7, 2.4, 
       3.3, 2.5, 2.3, 1.9, 1.8, 2.3)
y <- c(2.5, 5.8, 2.1, -3, 12, 5, 6.2,
       4.8, 4.2, 3.5, 3.7, 5.2)

# Plotting the graph
plot(x, y, cex = 1, pch = 3,
     xlab ="x", ylab ="y",
     col ="black")

lines(x, y, col = "red")

Output: 

Example 3: Adding Horizontal and Vertical Lines Using abline()

In other situations, you might prefer adding vertical or horizontal lines to the plot without calling lines(). The abline() function is helpful for drawing horizontal, vertical, or diagonal lines to the plot.

R
# Create some sample data
      x <- 1:10
      y <- x^2
plot(x, y)

# Add a vertical line at x = 5
abline(v = 5)

# Add a horizontal line at y = 25
abline(h = 25)

# Add a diagonal line with slope 1 and intercept 0
abline(a = 0, b = 1)

# Add a line using the lines() function
   x2 <- 1:10
   y2 <- 2*x2 + 3
   lines(x2, y2, col = "red", lty = 2)

Output

vertical-lines-abline

Vertical lines using abline()

Related Articles:



Next Article
Article Tags :

Similar Reads