Ordering categorical bars in facetted plots

dplyr
ggplot2

#1

Basically, how do I order bars in a facetted plot?

E.G

library(tidyverse)
library(nycflights13)

flights %>%
  group_by(carrier, dest) %>%
  summarise(n = n()) %>%
  top_n(n = 5, wt = n) %>%
  filter(carrier %in% c("DL", "B6", "EV", "MQ")) %>%
  ggplot(aes(x = dest, y = n, fill = n)) +
  geom_col() +
  facet_wrap(~carrier, scales = "free_x")

I would like the bars to line up in order within each facet. I feel like I’ve realised that the issue is that the ordering is done pre-facetting? So because ‘ATL’ is the most frequent, in the facets where ATL appears, it will be at the top, even if it isn’t within that facet. So how do you work around it?

I have tried:

flights %>%
  group_by(carrier, dest) %>%
  summarise(n = n()) %>%
  top_n(n = 5, wt = n) %>%
  filter(carrier %in% c("DL", "B6", "EV", "MQ")) %>%
  ggplot(aes(x = reorder(dest, n), y = n, fill = n)) +
  geom_col() +
  facet_wrap(~carrier, scales = "free_x")


and

flights %>%
  group_by(carrier, dest) %>%
  summarise(n = n()) %>%
  top_n(n = 5, wt = n) %>%
  filter(carrier %in% c("DL", "B6", "EV", "MQ")) %>%
  mutate(dest = fct_reorder(dest, n)) %>%
  ggplot(aes(x = dest, y = n, fill = n)) +
  geom_col() +
  facet_wrap(~carrier, scales = "free_x")

and

flights %>%
  group_by(carrier, dest) %>%
  summarise(n = n()) %>%
  top_n(n = 5, wt = n) %>%
  filter(carrier %in% c("DL", "B6", "EV", "MQ")) %>%
  arrange(-n, dest, carrier) %>%
  ggplot(aes(x = dest, y = n, fill = n)) +
  geom_col() +
  facet_wrap(~carrier, scales = "free_x")

And combinations of the above, but it never comes out right.

Any clues?


#2

Hi @eldenvo,

I think this post will provide some insight about this common issue: Ordering Categories within ggplot2 Facets

The approach was later generalized by @drob https://github.com/dgrtwo/drlib/blob/master/R/reorder_within.R

Hope it helps!