Facetting is a process that combines data sub-setting and data visualization.
Data
The diamonds dataset that ships with ggplot.
Plot Syntax: facet_grid
Facets are multiple small plots, each representing a slice of data. Facetting is a powerful data analysis and exploration tool. facet_grid produces a lattice grid of plot panels with basic row and column identifiers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
library(ggplot) # Plot skeleton p <- ggplot(diamonds, aes(carat, price, color = cut)) # Plot1: Raw data with no facets p + geom_point(size = 1.5, alpha = 0.75) # Plot2: facet_grid with diamond cut on columns p + geom_point(size=1.5, alpha = 0.75) + facet_grid( . ~ cut) # Plot3: facet_grid with diamond cut on rows p + geom_point(size=1, alpha = 0.75) + facet_grid(cut ~ .) # Plot 4: facet_grid with diamond cut by diamond clarity p + geom_point(size=1, alpha=0.75) + facet_grid(cut ~ clarity) |
Plot Syntax: facet_wrap
facet_wrap takes a strip of plot panels and wraps them by row into a lattice. Function arguments control the number of rows or columns that guide panel wrapping:
1 2 3 4 5 |
# Plot7: simple facet_wrap p + geom_point(size=1, alpha=0.75) + facet_wrap(~ cut) # Plot8: facet wrap with 2 columns p + geom_point(size=1, alpha=0.75) + facet_wrap(~ cut, ncol=2) |
Aesthetics
The arguments to facet_grid that control plot aesthetics are:
1 2 3 |
facet_grid(facets, margins = FALSE, scales = "fixed", space = "fixed", shrink = TRUE, labeller = "label_value", as.table = TRUE, drop = TRUE) |
The aesthetic arguments to facet_wrap are:
1 2 3 |
facet_wrap(facets, nrow = NULL, ncol = NULL, scales = "fixed", shrink = TRUE, as.table = TRUE, drop = TRUE) |
Modifying Label Text
Changes to panel label text are possible and require changes to the factors that comprise the input data set. For example:
1 2 3 4 5 6 7 8 9 |
# Change label text with new factor levels levels(diamonds$cut)[levels(diamonds$cut)=="Ideal"] <- "Maximum Fire" levels(diamonds$cut)[levels(diamonds$cut)=="Premium"] <- "Superior Light" levels(diamonds$cut)[levels(diamonds$cut)=="Very Good"] <- "Average Light" levels(diamonds$cut)[levels(diamonds$cut)=="Good"] <- "Weak Light" levels(diamonds$cut)[levels(diamonds$cut)=="Fair"] <- "No Fire" ggplot(diamonds, aes(carat, price, color=cut)) + geom_point(size=1, alpha = 0.75) + facet_grid(cut ~ .) |
Modifying Label Formats
Label format changes require changes to theme formats, or the default formats behind ggplot.
1 2 3 4 |
# Change lable formats ggplot(diamonds, aes(carat, price, color=cut)) + geom_point(size=1, alpha = 0.75) + facet_grid(cut ~ .) + theme(strip.text.y = element_text(size=12, face="bold", color="white"), strip.background = element_rect(colour="green", fill="grey25")) |