Home » How to Overlay Plots in R (With Examples)

How to Overlay Plots in R (With Examples)

by Erma Khan

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 here.

Additional Resources

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

How to Plot Multiple Boxplots in One Chart in R
How to Plot Multiple Lines in One Chart in R

Related Posts