R Difference Between ggplot2’s facet_wrap & facet_grid Explained (2 Examples)
In this article you’ll learn how to use the facet_grid and facet_wrap functions of the ggplot2 package in the R programming language.
Setting up the Examples
data(iris) # Loading iris data set iris_new <- iris # Modify iris iris_new$subgroup <- rep(letters[1:2], each = 75) head(iris_new) # Head of example data # Sepal.Length Sepal.Width Petal.Length Petal.Width Species subgroup # 1 5.1 3.5 1.4 0.2 setosa a # 2 4.9 3.0 1.4 0.2 setosa a # 3 4.7 3.2 1.3 0.2 setosa a # 4 4.6 3.1 1.5 0.2 setosa a # 5 5.0 3.6 1.4 0.2 setosa a # 6 5.4 3.9 1.7 0.4 setosa a |
data(iris) # Loading iris data set iris_new <- iris # Modify iris iris_new$subgroup <- rep(letters[1:2], each = 75) head(iris_new) # Head of example data # Sepal.Length Sepal.Width Petal.Length Petal.Width Species subgroup # 1 5.1 3.5 1.4 0.2 setosa a # 2 4.9 3.0 1.4 0.2 setosa a # 3 4.7 3.2 1.3 0.2 setosa a # 4 4.6 3.1 1.5 0.2 setosa a # 5 5.0 3.6 1.4 0.2 setosa a # 6 5.4 3.9 1.7 0.4 setosa a
install.packages("ggplot2") # Install ggplot2 package library("ggplot2") # Load ggplot2 |
install.packages("ggplot2") # Install ggplot2 package library("ggplot2") # Load ggplot2
my_plot <- ggplot(iris_new, aes(x = Petal.Length, y = Petal.Width)) + # Create plot without facets geom_line() |
my_plot <- ggplot(iris_new, aes(x = Petal.Length, y = Petal.Width)) + # Create plot without facets geom_line()
Example 1: Apply facet_wrap() Function of ggplot2 Package
my_plot + # facet_wrap facet_wrap(Species ~ subgroup) |
my_plot + # facet_wrap facet_wrap(Species ~ subgroup)
Example 2: Apply facet_grid() Function of ggplot2 Package
my_plot + # facet_grid facet_grid(Species ~ subgroup) |
my_plot + # facet_grid facet_grid(Species ~ subgroup)