R How to Draw a ggplot2 Plot from 2 Different Data Sources in R (Example Code)
In this tutorial you’ll learn how to create a ggplot2 graph with two different data sets in the R programming language.
Preparing the Example
data(iris) # Load iris data data(mtcars) # Load mtcars data |
data(iris) # Load iris data data(mtcars) # Load mtcars data
install.packages("ggplot2") # Install & load ggplot2 library("ggplot2") |
install.packages("ggplot2") # Install & load ggplot2 library("ggplot2")
Example: Creating ggplot2 Plot with Two Different Data Frames
You have to specify NULL within the ggplot function. Then, you have to specify the different data sets within the geom_point and geom_line functions.
my_plot <- ggplot(NULL) + # Printing ggplot2 grphic based on 2 data sets geom_point(data = iris, aes(x = Sepal.Length, y = Sepal.Width), col = "purple") + geom_line(data = mtcars, aes(x = cyl, y = drat), col = "orange") my_plot # Creating ggplot2 plot |
my_plot <- ggplot(NULL) + # Printing ggplot2 grphic based on 2 data sets geom_point(data = iris, aes(x = Sepal.Length, y = Sepal.Width), col = "purple") + geom_line(data = mtcars, aes(x = cyl, y = drat), col = "orange") my_plot # Creating ggplot2 plot