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?