Reorder columns within facet

I'd like to sort my faceted bar charts in descending order. I've tried using Julia Silge's excellent resource here, but I'm clearly doing something wrong because the bars still fail to sort. Thanks in advance for any help.

library(tidyverse)
library(scales)
library(tidytext)

award_totals <- structure(list(department = c("Middle & Secondary Ed", "Counseling", 
"148120000", "Middle & Secondary Ed", "Dean's Office", "Dean's Office", 
"Middle & Secondary Ed", "148120000", "Kinesiology", "Middle & Secondary Ed", 
"Dean's Office", "Dean's Office", "Middle & Secondary Ed", "Early Childhood", 
"Dean's Office", "Dean's Office", "Middle & Secondary Ed", "Early Childhood", 
"Early Childhood", "Dean's Office", "Dean's Office", "Early Childhood", 
"Dean's Office", "Dean's Office", "Dean's Office"), amount_awarded = c(3703153, 
3622500, 1467126, 1306477, 1076361, 3450762, 2843601, 1484672, 
1461513, 1261592, 3450763, 2998743, 2390311, 2282729, 1150254, 
3450763, 1999328, 1771780, 1698255, 1150254, 3e+06, 1689019, 
1527302, 1516448, 1e+06), fiscal_year = structure(c(5L, 5L, 5L, 
5L, 5L, 4L, 4L, 4L, 4L, 4L, 3L, 3L, 3L, 3L, 3L, 2L, 2L, 2L, 2L, 
2L, 1L, 1L, 1L, 1L, 1L), levels = c("FY18", "FY19", "FY20", "FY21", 
"FY22"), class = "factor")), row.names = c(NA, -25L), class = c("tbl_df", 
"tbl", "data.frame"))

award_totals %>%   
  mutate(fiscal_year = as.factor(fiscal_year),
         department = reorder_within(department, amount_awarded, fiscal_year)) %>% 
  ggplot(aes(x = department, y = amount_awarded, fill = fiscal_year)) + 
  geom_col(show.legend = FALSE) +
  facet_wrap(~fiscal_year, scales = "free_y") +
  scale_y_continuous(labels = dollar_format()) +
  labs(x = "",
       y= "Amount awarded") +
  coord_flip()

I think adding fun = sum to replace the default fun = mean in reorder_within() will work

You were right. Thank you!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.