首页 > 解决方案 > 如何通过ggplot中每个方面的x轴值对箱线图进行排序?

问题描述

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

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

我在这里想念什么?

标签: rggplot2forcats

解决方案


谢谢Tung,那个链接给了我线索!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 值?有没有办法解决这个问题?


推荐阅读