ggplot2 Facets

Data Visualizationggplot2Free Lesson

Advertisement

Introduction

Facets create subplots based on categorical variables. They're essential for comparing groups.

Facet Grid

ggplot(df, aes(x, y)) + geom_point() +
  facet_grid(. ~ category)

# Vertical facets
ggplot(df, aes(x, y)) + geom_point() +
  facet_grid(category ~ .)

Facet Wrap

# Wrap in grid
ggplot(df, aes(x, y)) + geom_point() +
  facet_wrap(~ category)

# Multiple variables
ggplot(df, aes(x, y)) + geom_point() +
  facet_wrap(~ category + group)

# Control rows/cols
ggplot(df, aes(x, y)) + geom_point() +
  facet_wrap(~ category, nrow = 2, ncol = 3)

Faceting Options

# Same scales (default)
ggplot(df, aes(x, y)) + geom_point() +
  facet_wrap(~ category, scales = "free")

# Free x/y scales
ggplot(df, aes(x, y)) + geom_point() +
  facet_wrap(~ category, scales = "free_x")

# Labels
ggplot(df, aes(x, y)) + geom_point() +
  facet_wrap(~ category, 
             labeller = label_both)

Summary

Facets enable multi-panel plots. Use them to compare groups effectively.

Advertisement

Need Expert R Programming Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement