Section 39 Multiple Plot Layout using ggplot2: facet_grid

The function facet_grid forms a matrix of panels defined by row and column facetting variables. It is most useful when you have two discrete variables, and all combinations of the variables exist in the data.

39.1 Function

facet_grid(facets, margins = FALSE, scales = "fixed", space = "fixed", shrink = TRUE, labeller = "label_value", as.table = TRUE, switch = NULL, drop = TRUE)

39.2 Columns

g <- ggplot(mpg, aes(displ, cty)) + geom_point()

g + facet_grid(. ~ cyl) + theme_bw()

39.3 Rows

g + facet_grid(drv ~ .) + theme_bw()

39.4 Rows x Columns

g + facet_grid(drv ~ cyl) + theme_bw()

39.5 scales = "free"

g <- ggplot(mtcars, aes(mpg, wt, colour = factor(cyl)))
g <- g + geom_point()
g + facet_grid(. ~ cyl, scales = "free") + theme_bw()

39.6 Multiple row variables

g <- ggplot(mtcars, aes(mpg, wt, colour = factor(cyl)))
g <- g + geom_point()
g + facet_grid(vs + am ~ gear) + theme_bw()

Note: Use the labeller option to control how labels are printed on the panels.