16.2 Facet grid

facet_grid() lays out plots in a 2d grid, as defined by a formula:

  • . ~ a spreads the values of a across the columns. This direction
    facilitates comparisons of y position, because the vertical scales are aligned.

    base + facet_grid(. ~ cyl)

  • b ~ . spreads the values of b down the rows. This direction facilitates comparison of x position because the horizontal scales are aligned. This makes it particularly useful for comparing distributions.

    base + facet_grid(drv ~ .)

  • a ~ b spreads a across columns and b down rows. You’ll usually want to put the variable with the greatest number of levels in the columns, to take advantage of the aspect ratio of your screen.

    base + facet_grid(drv ~ cyl)

You can use multiple variables in the rows or columns, by “adding” them together, e.g. a + b ~ c + d. Variables appearing together on the rows or columns are nested in the sense that only combinations that appear in the data will appear in the plot. Variables that are specified on rows and columns will be crossed: all combinations will be shown, including those that didn’t appear in the original dataset: this may result in empty panels.