Facet wrap & margins

Intermediate Data Visualization with ggplot2

Rick Scavetta

Founder, Scavetta Academy

Adjusting the plotting space

ggplot(msleep2, aes(bodywt_log, 
                    brainwt_log)) +
  geom_point(alpha = 0.6, shape = 16) +
  facet_grid(rows = vars(vore), 
             cols = vars(conservation),
             scales = "free") 

Intermediate Data Visualization with ggplot2

Using facet_wrap()

Use cases:

  1. When you want both x and y axes to be free on every individual plot
    • i.e. Not just per row or column as per facet_grid()
Intermediate Data Visualization with ggplot2

Using facet_wrap() - Scenario 1

ggplot(msleep2, aes(bodywt_log, 
                    brainwt_log)) +
  geom_point(alpha = 0.6, shape = 16) +
  facet_wrap(vars(vore, conservation),
             scales = "free") 

Intermediate Data Visualization with ggplot2

Using facet_wrap()

Use cases:

  1. When you want both x and y axes to be free on every individual plot
    • i.e. Not just per row or column as per facet_grid()
  2. When your categorical (factor) variable has many groups (levels)
    • i.e. too many sub plots for column or row-wise faceting
    • A more typical scenario
Intermediate Data Visualization with ggplot2

Using facet_wrap() - Scenario 2

ggplot(msleep2, aes(bodywt_log, 
                    brainwt_log)) +
  geom_point(alpha = 0.6, shape = 16) +
  facet_wrap(vars(order))

Intermediate Data Visualization with ggplot2

Using margin plots

ggplot(msleep2, aes(bodywt_log, 
                    brainwt_log)) +
  geom_point(alpha = 0.6, shape = 16) +
  facet_grid(rows = vars(vore), 
             cols = vars(conservation),
             scales = "free") 

Intermediate Data Visualization with ggplot2

Using margin plots

ggplot(msleep2, aes(bodywt_log, 
                    brainwt_log)) +
  geom_point(alpha = 0.6, shape = 16) +
  facet_grid(rows = vars(vore), 
             cols = vars(conservation),
             scales = "free",
             margins = TRUE) 

Intermediate Data Visualization with ggplot2

Using margin plots

ggplot(msleep2, aes(bodywt_log, 
                    brainwt_log)) +
  geom_point(alpha = 0.6, shape = 16) +
  facet_grid(rows = vars(vore), 
             cols = vars(conservation),
             scales = "free",
             margins = "conservation")

Intermediate Data Visualization with ggplot2

Let's practice!

Intermediate Data Visualization with ggplot2

Preparing Video For Download...