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

r graph figure 1 r draw ggplot2 from 2 different data sources r

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top