You can use the points() function to add points to an existing plot in R.
This function uses the following basic syntax:
points(df2$x, df2$y, col='red')
This particular syntax adds red points to an existing scatter plot in R using the variables called x and y from a data frame called df2.
The following example shows how to use this syntax in practice.
Example: Add Points to an Existing Plot in R
Suppose we use the plot() function to create the following scatter plot in R:
#create data frame df1 <- data.frame(x=c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), y=c(4, 5, 5, 4, 6, 8, 12, 15, 19, 22)) #create scatterplot plot(df1$x, df1$y, col='blue', pch=16)
Note: The col argument specifies the color of the points in the plot and the pch argument specifies the symbol to use. A value of 16 represents a filled-in circle.
Now suppose that we would like to add points from another data frame to the plot.
We can use the points() function to do so:
#create second data frame df2 <- data.frame(x=c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), y=c(14, 12, 9, 9, 8, 5, 4, 5, 3, 2)) #add points from df2 to the existing scatter plot points(df2$x, df2$y, col='red', pch=16)
Notice that the points from the second data frame have been added to the existing plot and are represented by a red color.
If we’d like, we can also use the legend() function to add a legend to the plot so that we can distinguish which points came from which data frame:
#add legend to plot legend(x=1, y=22, legend=c('df1', 'df2'), fill=c('blue', 'red'))
Note: You can use the points() function as many times as you’d like to add points from as many data frames as you’d like to an existing plot.
The following tutorials explain how to perform other common tasks in R: