In this tutorial, we will learn how to change the order of panes in a plot made with facet_wrap() or facet_grid(). We will use forcats package’s function fct_relevel() to specify the order we want while plotting.
library(palmerpenguins) library(tidyverse) theme_set(theme_bw(16))
penguins |> head() # A tibble: 6 × 8 species island bill_length_mm bill_depth_mm flipper_length_mm body_mass_g <fct> <fct> <dbl> <dbl> <int> <int> 1 Adelie Torgersen 39.1 18.7 181 3750 2 Adelie Torgersen 39.5 17.4 186 3800 3 Adelie Torgersen 40.3 18 195 3250 4 Adelie Torgersen NA NA NA NA 5 Adelie Torgersen 36.7 19.3 193 3450 6 Adelie Torgersen 39.3 20.6 190 3650 # ℹ 2 more variables: sex <fct>, year <int>
Let us make a scatterplot with facets using facet_wrap() function in ggplot2.
penguins |> drop_na() |> ggplot(aes(x=bill_length_mm, body_mass_g, color=sex))+ geom_point()+ geom_smooth(method="lm")+ theme(legend.position = "bottom")+ facet_wrap(~species, scales = "free_x") ggsave("how_to_specify_order_of_plots_in_facet_wrap.png")
Change order of plots in facet_wrap() with fct_relevel()
We specify the order of panes in the plot by using fct_relevel() inside facet_wrap() function.
penguins |> drop_na() |> ggplot(aes(x=bill_length_mm, body_mass_g, color=sex))+ geom_point()+ geom_smooth(method="lm")+ #facet_wrap(~species)+ theme(legend.position = "bottom")+ facet_wrap(~forcats::fct_relevel(species, "Gentoo", "Adelie", "Chinstrap"), scales = "free_x") ggsave("specify_order_of_plots_with_fct_relevel_facet_wrap.png")
If you are interested in simply reversing the order of plots in facet_wrap(), we can use forcats’ fct_rev() function as shown in this post