1

Don't think this is a duplicate of others, but happy to delete if it is.

Dataset contains 3 columns: 'Recipient' (x-axis), 'Amount' (y-axis), and 'Department'(grid-column/fill).

How can I re-order facet grids more intuitively in descending order by total 'Amount' spent for each 'Department'? (Blue first, since it has spent the most 'Amount' & has the highest # of 'Recipients', probably followed by turquoise, then green, etc.)

enter image description here

R script:

library("tidyverse")
library("ggthemes")
library("gganimate")
library("readxl")
library("httr")
library("rvest")
library("scales")
library("tidytext")

source_file <- "Houston City Council 2020-06-16.xlsx"

agenda_prime <- read_xlsx(source_file, sheet = 6, col_names = TRUE)

agenda_reordered <- agenda_prime %>% 
#   mutate(Recipient = fct_reorder(Recipient, desc(Amount)))
    mutate(
        Recipient = reorder_within(Recipient, desc(Amount), Department))

plot <- agenda_reordered %>%
    ggplot(aes(Recipient, Amount, fill = Department, label = dollar(Amount))) +
    geom_col(show.legend = FALSE) + 
    labs(title = "$ spent during this week's City Council meeting", 
        subtitle = "Wednesday, June 17, 2020",
        caption = "Sources: City of Houston, City Council Agenda, June 16 & 17, 2020 & HTV broadcast of 6/17 agenda session",
        x = "",
        y = "") +
    theme_solarized_2(light = FALSE) +
    theme(legend.position = "top", legend.direction = "horizontal", legend.title = element_blank()) +
    scale_y_continuous(labels = dollar_format(prefix = "$")) +
#   geom_text(aes(Vote, Number+3), size = 3, color = "gray")
    facet_grid(cols = vars(Department), scales = "free_x", space = "free_x") +
    theme(strip.text.x = element_blank(), strip.background = element_blank(), axis.text.x = element_text(angle=0, size=2))

plot

Source dataset:

enter image description here

THANKS!!!

owlstone
  • 533
  • 1
  • 4
  • 11
  • I think the forcats package has a reorder function you want, but I’m on my mobile so can’t code, but not sure about for different variables or in ggplot(aes(x=reorder(variables))) – Daniel_j_iii Jun 19 '20 at 03:44
  • 1
    You're already reordering `Recipient`, which you have on the x-axis, and it looks good.You want your facets ordered, and you facet by `Department`, so you need to `reorder` that variable too. If you want it reordered by the `sum` of `Amount`, then add to your mutate `Department = reorder(Department, Amount, sum)`. – Gregor Thomas Jun 19 '20 at 04:17

0 Answers0