ggplot2 Plot of Two Data Frames with Different Sizes in R (Example Code)
In this article you’ll learn how to draw a ggplot2 graphic of two data frames with different number of rows in R programming.
Creation of Example Data
data(iris) # Load & construct example data |
data(iris) # Load & construct example data
set.seed(3285638) # Set seed |
set.seed(3285638) # Set seed
iris_1 <- iris[sample(1:nrow(iris), 100), ] # Sample first data frame head(iris_1) # Sepal.Length Sepal.Width Petal.Length Petal.Width Species # 67 5.6 3.0 4.5 1.5 versicolor # 52 6.4 3.2 4.5 1.5 versicolor # 119 7.7 2.6 6.9 2.3 virginica # 45 5.1 3.8 1.9 0.4 setosa # 33 5.2 4.1 1.5 0.1 setosa # 79 6.0 2.9 4.5 1.5 versicolor |
iris_1 <- iris[sample(1:nrow(iris), 100), ] # Sample first data frame head(iris_1) # Sepal.Length Sepal.Width Petal.Length Petal.Width Species # 67 5.6 3.0 4.5 1.5 versicolor # 52 6.4 3.2 4.5 1.5 versicolor # 119 7.7 2.6 6.9 2.3 virginica # 45 5.1 3.8 1.9 0.4 setosa # 33 5.2 4.1 1.5 0.1 setosa # 79 6.0 2.9 4.5 1.5 versicolor
iris_2 <- iris[sample(1:nrow(iris), 10), ] # Sample second data frame head(iris_2) # Sepal.Length Sepal.Width Petal.Length Petal.Width Species # 27 5.0 3.4 1.6 0.4 setosa # 58 4.9 2.4 3.3 1.0 versicolor # 133 6.4 2.8 5.6 2.2 virginica # 59 6.6 2.9 4.6 1.3 versicolor # 86 6.0 3.4 4.5 1.6 versicolor # 108 7.3 2.9 6.3 1.8 virginica |
iris_2 <- iris[sample(1:nrow(iris), 10), ] # Sample second data frame head(iris_2) # Sepal.Length Sepal.Width Petal.Length Petal.Width Species # 27 5.0 3.4 1.6 0.4 setosa # 58 4.9 2.4 3.3 1.0 versicolor # 133 6.4 2.8 5.6 2.2 virginica # 59 6.6 2.9 4.6 1.3 versicolor # 86 6.0 3.4 4.5 1.6 versicolor # 108 7.3 2.9 6.3 1.8 virginica
Example: Draw Two Data Sets with Different Sizes Using ggplot2 Package
install.packages("ggplot2") # Install ggplot2 package library("ggplot2") # Load ggplot2 package |
install.packages("ggplot2") # Install ggplot2 package library("ggplot2") # Load ggplot2 package
ggplot(NULL, # Draw ggplot2 plot using two data frames aes(x = Sepal.Length, y = Sepal.Width)) + geom_point(data = iris_1, col = 1, pch = 1, size = 1) + geom_point(data = iris_2, col = 2, pch = 2, size = 2) |
ggplot(NULL, # Draw ggplot2 plot using two data frames aes(x = Sepal.Length, y = Sepal.Width)) + geom_point(data = iris_1, col = 1, pch = 1, size = 1) + geom_point(data = iris_2, col = 2, pch = 2, size = 2)
Related Articles
Please find some related R programming tutorials on topics such as time objects, graphics in R, and variables in the following list.