I'm using {highcharter}
which is fussy about row order and not factors ()
Here's a fake dataset that produces exactly the chart I want:
- The y-axis (responses) are ordered by their appearance in the most recent year
library("tidyverse")
library("highcharter")
correct_ordered_data <- tribble(
~response, ~year, ~count, ~color, ~order,
"Left shoe", 2019, 20, "yellow", 1,
"Left shoe", 2018, 25, "yellow", 2,
"Right shoe", 2019, 18, "yellow", 2,
"Right shoe", 2018, 27, "yellow", 1,
"Velcro", 2019, 12, "yellow", 3,
"Velcro", 2018, 22, "yellop", 3,
"OTHER", 2019, 0, "yellow", 1000,
"OTHER", 2018, 10, "yellow", 1000
)
correct_ordered_data %>%
hchart(
type = "bar",
hcaes(
x = response,
y = count,
group = year
)
) %>%
hc_legend(reversed = FALSE) %>%
hc_xAxis(reversedStacks = TRUE)
Now I'll jumble up the data:
badly_ordered_data <- correct_ordered_data %>%
arrange(year)
My current solution for re-ordering this is a requires a utility variable:
most_recent_order <- badly_ordered_data %>%
filter(year == max(year)) %>%
arrange(order) %>%
select(response) %>%
mutate(most_recent_year_order = row_number())
reordered_data <- badly_ordered_data %>%
left_join(most_recent_order) %>%
arrange(most_recent_year_order, desc(year)) %>%
select(-most_recent_year_order)
I can prove I've got back what I wanted as follows:
reordered_data == correct_ordered_data
I'd very much appreciate advice on a smarter way to order data like this, thanks!