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

r graph figure 1 r difference between ggplot2's facet_wrap facet_grid explained

Example 1: Apply facet_wrap() Function of ggplot2 Package

my_plot +                                    # facet_wrap
  facet_wrap(Species ~ subgroup)

r graph figure 2 r difference between ggplot2's facet_wrap facet_grid explained

Example 2: Apply facet_grid() Function of ggplot2 Package

my_plot +                                    # facet_grid
  facet_grid(Species ~ subgroup)

r graph figure 3 r difference between ggplot2's facet_wrap facet_grid explained

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