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


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.

Additional Resources

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

How to Use abline() in R to Add Straight Lines to Plots
How to Create a Scatterplot with a Regression Line in R
How to Adjust Line Thickness in ggplot2

Leave a Reply

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