What is the difference between facet_wrap() and facet_grid() in ggplot?

Asked

Viewed 107 times

3

The options facet_wrap() and facet_grid() in the ggplot have similar purposes, produce graphs with results stratified by a categorical variable. However, sometimes these options produce aesthetically identical results, sometimes similar, sometimes very different.

What is the difference in rationality behind these two options? Is there any criterion for choosing one of the two?

Example of identical result:

library(ggplot2)

g1 <- ggplot(iris, aes(Sepal.Width, Sepal.Length)) + 
  geom_point()

g1 + facet_wrap(~ Species)

g1 + facet_grid(~ Species)

Example of similar result:

g2 <- ggplot(mpg, aes(displ, hwy)) +
  geom_point()

g2 + facet_wrap(~cyl)

g2 + facet_grid(~cyl)

Example of different result:

g2 <- ggplot(mpg, aes(displ, hwy)) +
  geom_point()

g2 + facet_wrap(cyl~class)

g2 + facet_grid(cyl~class)

1 answer

5


What is the difference of rationality behind these two options?

facet_wrap transforms a sequence of one-dimensional panels into something in two dimensions, while facet_grid creates an array of panels. Using the question examples, we have

library(ggplot2)

g2 <- ggplot(mpg, aes(displ, hwy)) +
    geom_point()

g2 + facet_wrap(cyl~class)

g2 + facet_grid(cyl~class)

Created on 2020-10-27 by the reprex package (v0.3.0)

Note that when using facet_wrap, the combinations between cyl and class are placed together, in the title of each panel, so that they could be lined up, in one dimension, no problem any identification of which is each panel.

On the other hand, when using facet_grid, an array of panels is created with all combinations of levels of the considered categorical variables. Note that there are more panels with facet_grid than with facet_wrap, but these extra panels are empty.

For this reason, in the vast majority of times, it makes no difference to use facet_wrap or facet_grid if only one categorical variable is used to create the panels.

Is there any criterion for choosing one of the two?

Apart from some aesthetic preference, I see no reason to choose one or the other. Both display the same information, although I prefer the result of facet_grid when there is information to display in all possible combinations. Otherwise, use facet_wrap to save space by automatically discarding cases that do not occur.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.