# packages and global themelibrary(ggplot2)library(dplyr)
theme_set(theme_bw() + theme(# make subplot titles more prominent strip.text = element_text(size = 14, face = "bold")))
Change the Order of Faceted Panels (Subplots) in ggplot2
In this earlier tutorial, you learned four powerful approaches to reorder a bar graph in ggplot2. These four approaches are broadly applicable to reorder other graphical elements. And in this article, we’ll use these techniques to reorder faceted panels (subplots).
By default, faceted panels are arranged in the alphabetical order of the subplot titles.
%>% iris ggplot(aes(Sepal.Length, Sepal.Width)) + geom_point(alpha = .2, size = 6, color = "turquoise4") + facet_wrap(~Species)
To reorder the faceted panels, the generic approach is to convert the faceting variable, e.g., Species
, into a factor with specified level order, before feeding the dataset into ggplot2. Below you’ll learn how to rearrange the faceted panels:
“Manually” reorder faceted panels in a particular order
In this example, the setosa
species is relocated from the first to the last panel. This is achieved by using the mutate()
and factor()
function, with explicitly indicated levels’ order.
%>% iris mutate(Species = factor( Species, # specify the desired order to be displayed levels = c("versicolor", "virginica", "setosa"))) %>% ggplot(aes(Sepal.Length, Sepal.Width)) + geom_point(alpha = .2, size = 6, color = "turquoise4") + facet_wrap(~Species)
Reorder faceted panels based on summary statistics
An earlier tutorial discussed how to reorder violin plots based on group statistics using the fct_reorder()
function from the forcats
package. Using the same technique, you can easily change the subplots order, for instance, based on the average of the Sepal.Width
variable in an ascending order.
This following code generates the same plot as the one above.
library(forcats)
%>% iris # reorder the 'Species' variable by the average of 'Sepal.Width' mutate(Species = fct_reorder(Species, Sepal.Width, .fun = mean)) %>% ggplot(aes(Sepal.Length, Sepal.Width)) + geom_point(alpha = .2, size = 6, color = "turquoise4") + facet_wrap(~Species)
Apply Your Learning in Practice! 🏆
The following faceted line plots (of different continents) applies the same facet reordering technique discussed above, and effectively displays the differences in life expectancy between different continents.
Continue Exploring — 🚀 one level up!
The geofacet
package developed by Ryan Hafen is a fascinating ggplot2 extension package that allows reordering faceted subplots in a map layout. Check the following faceted donut plots in a U.S. map layout that visualize the voting results of the 2016 U.S. presidential election in each state.