The lines() function in R draws lines on a plot. You can use this function to add straight lines, curved lines, or even create shapes on your plot. This guide will explain how to use the lines() function in R.
Syntax
lines(x, y, col, lty)
Arguments
- x = vector of the x-coordinates of the points to connect
- y = vector of the y-coordinates of the points to connect
- col = color of the line
- lty = the type of line to draw. Solid is the default type of line. Use the following to define the type:
- blank = 0 or “blank”
- solid = 1 or “solid
- dashed = 2 or “dashed”
- dotted = 3 “dotted”
- dotdash= 4 or “dotdash”
- longdash = 5 or “longdash”
- twodash = 6 or “twodash”
Example 1: Adding a Line to a Plot
In this first example, we’ll use the lines function to add a line to a plot. We’ll create a basic plot using the plot function and then use the lines function to add a line.
# creating variables x = c(1,2,3,4,5,6,7,8,9,10) y = c(1,4,9,16,25,36,49,64,81,100) # plotting the chart plot(x,y) # adding lines to the chart lines(x,y)
Output
Example 2: Adding Shapes to a Plot
In example, we’ll use the pch argument inside the plot function to add the shapes to a plot.
# creating variables x = c(1,2,3,4,5,6,7,8,9,10) y = c(1,4,9,16,25,36,49,64,81,100) # plotting the chart and adding star shape plot(x,y,pch=8) # adding lines to the chart lines(x,y)
Output
As you can see, the pch argument allows you to add shapes to your plot.
Example 3: Specifying the Type of Line
In this example, we’ll use the lines function to draw a dotted line. We’ll specify the lty argument as 2 to draw a dotted line.
# creating variables x = c(1,2,3,4,5,6,7,8,9,10) y = c(1,4,9,16,25,36,49,64,81,100) # plotting the chart plot(x,y) # adding a dotted line lines(x,y, lty=2)
Output
Example 4: Changing the Line Color
In this final example, we’ll use the lines function to draw a red line. We’ll specify the col argument as “red” to change the line color.
# creating variables x = c(1,2,3,4,5,6,7,8,9,10) y = c(1,4,9,16,25,36,49,64,81,100) # plotting the chart plot(x,y) # adding a red line to the chart lines(x,y, col= 'red')