How to Reverse Order in Facet in ggplot

How to reverse the order of facets in R
How to reverse the order of facets in R

In this tutorial, we will learn how to reverse the order of facets, multiple small plots, made with ggplot2 in R. We will use R package forcats’s handy function fct_rev() to reverse the order of facets made using facet_wrap() function in ggplot2.
Let us load tidyverse suite of R packages and palmer penguin dataset for making a plot with facets.

library(tidyverse)
library(palmerpenguins)
theme_set(theme_bw(16))

Simple Scatter Plot with Facets

Here we make a scatter plot facetted by third variable, by adding facet_wrap() function with the third variable

penguins %>%
  drop_na()%>%
  ggplot(aes(flipper_length_mm, body_mass_g, color = sex)) + 
  geom_point() +
  facet_wrap(~species)+
  theme(legend.position = "bottom")
ggsave("facet_wrap_example_ggplot2.png", width=9,height=6)
facetting with ggplot2

Reversing the order of Facets in ggplot2

In the previous plot we can see that, facets are ordered in alphabetical order by default. One of the ways to reverse the order of facets using forcats’ fct_rev() function while specifying the variable that we want to facet by. In this example, we used fct_rev(species) inside facet_wrap(), like facet_wrap(~fct_rev(species)).

penguins %>%
  drop_na() %>%
  ggplot(aes(flipper_length_mm, body_mass_g, color = sex)) + 
  geom_point() +
  facet_wrap(~fct_rev(species))+
  theme(legend.position = "bottom")
ggsave("facet_wrap_reverse_order_example_ggplot2.png", width=9, height=6)
How to reverse the order of facets in R
Exit mobile version