Overlay Line Plots in R

To overlay a line plot in the R language, we use the lines() function. The lines() function is a generic function that overlays a line plot by taking coordinates from a data frame and joining the corresponding points with line segments. We can further customize that line plot by using the lty, lwd, and col parameters to customize line type, line width, and line color respectively.

Syntax:

points( x, y, ltype, lwd, col )

Parameter:

  • x and y: determines the x-axis and y-axis variables respectively.
  • lty: determines the line type.
  • lwd: determines the line width.
  • col: determines the color of line.

Example: Overlay line plots

R




# define sample data frames
sample_data <- data.frame(x=c(1, 2, 3, 4, 5),
                  y1 = c(7, 10, 26, 39, 5),
                  y2 = c(4, 14, 16, 29, 15),
                  y3 = c(2, 13, 36, 19, 25),
                  y4 = c(8, 11, 6, 9, 35))
                            
  
# create base scatter plot
plot(sample_data$x, sample_data$y1)
  
# overlay line plot 
lines(sample_data$x, sample_data$y2, col='green', lwd=2)
lines(sample_data$x, sample_data$y3, col='red', lwd=1)
lines(sample_data$x, sample_data$y4, col='blue', lty="dashed")


Output:

How to Overlay Plots in R?

In this article, we will discuss how to overlay plots in the R Programming Language.

Overlaying is a technique that is used to draw multiple plots on a single frame. To draw multiple plots in the R Language, we draw a basic plot and add an overlay line plot or scatter plot by using the lines() and the points() function. This line and scatter plot overlay can be drawn on top of any layer in the R Language.

Similar Reads

Method 1: Overlay Line Plots in R

To overlay a line plot in the R language, we use the lines() function. The lines() function is a generic function that overlays a line plot by taking coordinates from a data frame and joining the corresponding points with line segments. We can further customize that line plot by using the lty, lwd, and col parameters to customize line type, line width, and line color respectively....

Method 2: Overlay Scatter Plots in R

...

Contact Us