How to Use lines() Function in R (With Examples)

The lines() function in R is used to add lines to a graph. It takes various parameters such as start points, end points, color, line type, and size to draw the line. It can be used to draw lines between points, plot curves, and draw multiple lines. It can also be used to control the formatting of lines and points on a graph. This makes it an indispensable tool for data visualization in R.


You can use the lines() function in R to add new lines to an existing plot in base R.

This function uses the following syntax:

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

where:

  • x: Vector of x-coordinates to use for new line
  • y: Vector of y-coordinates to use for new line
  • col: Color of the new line
  • lwd: Width of the new line
  • lty: Line type for new line

The following example shows how to use the lines() function in practice.

Example: How to Use lines() Function in R

Suppose we use the following code to create a simple scatter plot in base R:

#define (x, y) coordinates
x <- c(1, 2, 3, 4, 5, 6, 7, 8)
y <- c(2, 5, 5, 9, 10, 14, 13, 15)

#create scatter plot
plot(x, y)

We can use the lines() function to add a line with specific (x, y) coordinates to the plot:

#define (x, y) coordinates
x <- c(1, 2, 3, 4, 5, 6, 7, 8)
y <- c(2, 5, 5, 9, 10, 14, 13, 15)

#create scatter plot
plot(x, y)

#define (x, y) coordinates for new line to add
x_line <- c(1, 2, 3, 4, 5, 6, 7, 8)
y_line <- c(2, 4, 6, 8, 10, 12, 14, 16)

#add new line to plot
lines(x_line, y_line)

We can also use the col, lwd and lty arguments to modify the color, line width, and line style of the new line:

#define (x, y) coordinates
x <- c(1, 2, 3, 4, 5, 6, 7, 8)
y <- c(2, 5, 5, 9, 10, 14, 13, 15)

#create scatter plot
plot(x, y)

#define (x, y) coordinates for new line to add
x_line <- c(1, 2, 3, 4, 5, 6, 7, 8)
y_line <- c(2, 4, 6, 8, 10, 12, 14, 16)

#add new line to plot with custom style
lines(x_line, y_line, col='red', lwd=6, lty='dashed')

Feel free to modify the values for the various arguments in the lines() function to add a new line with the exact style you’d like.

The following tutorials explain how to perform other common tasks in R:

x