Agenda


Libraries


library(ggplot2)

Facet - Intro


Generate subplots that each display one subset of the data using

  • facet_grid()
  • facet_wrap()

Columns


ggplot(mtcars, aes(disp, mpg)) + 
  geom_point() +
  facet_grid(. ~ cyl)

Rows


ggplot(mtcars, aes(disp, mpg)) + 
  geom_point() +
  facet_grid(cyl ~ .)

Rows & Columns


ggplot(mtcars, aes(disp, mpg)) + 
  geom_point() +
  facet_grid(gear ~ cyl)

Rows & Columns

ggplot(mtcars, aes(disp, mpg)) + 
  geom_point() +
  facet_grid(cyl ~ gear)

Scales


ggplot(mtcars, aes(disp, mpg, color = factor(cyl))) +
  geom_point() + 
  facet_grid(. ~ cyl, scales = "free")

Switch Axis


ggplot(mtcars, aes(disp, mpg)) + 
  geom_point() + 
  facet_grid(cyl ~ gear, switch = "both") 

Wrap


ggplot(mtcars, aes(disp, mpg)) +
  geom_point() +
  facet_wrap(~cyl)

Specify Rows


ggplot(mtcars, aes(disp, mpg)) +
  geom_point() +
  facet_wrap(~cyl, nrow = 2)

Specify Rows


ggplot(mtcars, aes(disp, mpg)) +
  geom_point() +
  facet_wrap(~cyl, nrow = 3)

Rows & Columns


ggplot(mtcars, aes(disp, mpg)) +
  geom_point() +
  facet_wrap(~cyl + gear)

Rows & Columns


ggplot(mtcars, aes(disp, mpg)) +
  geom_point() +
  facet_wrap(c("cyl", "gear"))

Scales


ggplot(mtcars, aes(disp, mpg)) +
  geom_point() +
  facet_wrap(~cyl, scales = "free")