Ordering and Filtering Facets
You'll learn how to control which facets appear and in what order, making your multi-panel plots more logical and impactful.
The Core Idea
By default, facet_wrap() and facet_grid() display facets alphabetically or in the order R encounters factor levels. But real data often has a natural or meaningful order—months should go January through December, not alphabetically; you might want to show only the top-performing categories; or arrange panels by median values rather than names.
You control facet order and selection through two key strategies:
1. Reordering Factor Levels
Before plotting, convert your faceting variable to a factor with levels in your desired order. R will respect this ordering when creating facets:
# Reorder based on another variable (e.g., median sales)
df$category <- reorder(df$category, df$sales, FUN = median)
# Or specify exact order manually
df$month <- factor(df$month, levels = c("Jan", "Feb", "Mar", ...))
2. Filtering Your Data
Simply subset your data before plotting to display only specific facets:
# Show only top 6 categories
top_categories <- df %>%
group_by(category) %>%
summarize(total = sum(sales)) %>%
top_n(6)
df_filtered <- df %>% filter(category %in% top_categories$category)
ggplot(df_filtered, aes(x = date, y = sales)) +
geom_line() +
facet_wrap(~category)
Think of it like arranging photo frames on a wall: you decide which photos to hang (filtering) and whether to arrange them chronologically, by importance, or any other logic (ordering).
Key Takeaway: Control facet order through factor-level reordering and control which facets display through data filtering—giving you precise command over your small multiples' narrative flow.