如何按 ggplot 中每个方面的 x 轴值对箱线图进行排序?

How to order boxplots by the x-axis-values within every facet in ggplot?

我想按每个方面(class 此处)内的 x 轴值(此处为 hwy)对箱线图进行排序。我尝试了 2 种方法,但都失败了:

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")

我在这里错过了什么?

感谢 Tung,link 给了我线索! tidytext 中的函数 reorder_within 在这里很有用:

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

...但现在唯一的问题是文本 _class 附加到图表上的每个 y-value?有办法解决这个问题吗?