0

I want to sort the boxplots by the x-axis-values (hwy here) within every facet (class here). I tried 2 methods, but failed:

library(tidyverse); library(forcats)

mpg %>% 
  ggplot(aes(x = hwy, y = fct_reorder(trans, hwy, median))) + 
  geom_boxplot() +
  facet_wrap(~class, scales = "free_y")

mpg %>% 
  group_by(class) %>% 
  mutate(trans = fct_reorder(trans, hwy, median)) %>%
  ungroup() %>% 
  ggplot(aes(x = hwy, y = trans)) + 
  geom_boxplot() +
  facet_wrap(~class, scales = "free_y")

What am I missing here?

Z.Lin
  • 28,055
  • 6
  • 54
  • 94
Geet
  • 2,515
  • 2
  • 19
  • 42
  • 2
    This might help https://stackoverflow.com/questions/52214071/how-to-order-data-by-value-within-ggplot-facets – Tung Sep 04 '20 at 21:49
  • Thanks Tung! I want to be able to use fct_reorder. Am i using it incorrectly? – Geet Sep 04 '20 at 21:55

1 Answers1

0

Thanks Tung, that link gave me the clue! The function reorder_within from the tidytext was useful here:

mpg %>% 
  ggplot(aes(x = hwy, y = tidytext::reorder_within(trans, hwy, class, median))) + 
  geom_boxplot() +
  facet_wrap(~class, scales = "free_y")

...but the only problem now is the text _class got attached to every y-value on the chart? Is there a way to fix that?

Geet
  • 2,515
  • 2
  • 19
  • 42