How to Overlay Plots in R?

Overlaying plots in R allows you to combine multiple plots on a single graphic. This can be done by using the plot() and lines() functions, which will add new plots to an existing graphic. By setting the parameters of the lines() function, such as color and linetype, you can change the appearance of the overlaid plots. It is also possible to add text and legends to the graphic to help identify the different plots.


You can use the lines() and points() functions to overlay multiple plots in R:

#create scatterplot of x1 vs. y1
plot(x1, y1)

#overlay line plot of x2 vs. y2
lines(x2, y2)

#overlay scatterplot of x3 vs. y3
points(x2, y2)

The following examples show how to use each of these functions in practice.

Example 1: How to Overlay Line Plots in R

The following code shows how to overlay three line plots in a single plot in R:

#define datasets
x1 = c(1, 3, 6, 8, 10)
y1 = c(7, 12, 16, 19, 25)

x2 = c(1, 3, 5, 7, 10)
y2 = c(9, 15, 18, 17, 20)

x3 = c(1, 2, 3, 5, 10)
y3 = c(5, 6, 7, 15, 18)

#create line plot of x1 vs. y1
plot(x1, y1, type='l', col='red')

#overlay line plot of x2 vs. y2
lines(x2, y2, col='blue')

#overlay line plot of x3 vs. y3
lines(x3, y3, col='purple')

#add legend
legend(1, 25, legend=c('Line 1', 'Line 2', 'Line 3'),
       col=c('red', 'blue', 'purple'), lty=1)

Overlaying line plots in R with legend

Example 2: How to Overlay Scatterplots in R

The following code shows how to overlay two scatterplots in a single plot in R:

#define datasets
x1 = c(1, 3, 6, 8, 10)
y1 = c(7, 12, 16, 19, 25)

x2 = c(1, 3, 5, 7, 10)
y2 = c(9, 15, 18, 17, 20)

#create scatterplot of x1 vs. y1
plot(x1, y1, col='red', pch=19)

#overlay scatterplot of x2 vs. y2
points(x2, y2, col='blue', pch=19)

#add legend
legend(1, 25, legend=c('Data 1', 'Data 2'), pch=c(19, 19), col=c('red', 'blue'))

Scatterplots overlayed in R with legend

Note that the pch argument specifies the shape of the points in the plot. A pch value of 19 specifies a filled-in circle.

You can find a complete list of pch values and their corresponding shapes .

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

x