根据观察计数对箱线图 x 轴重新排序

Reorder boxplot x-axis based on a count of observations

在这个简化的示例中,我可以获得期望的结果,即根据观察值的降序排列的 x 轴。

但是,为了处理更多的级别,这也会根据早期的过滤而有所不同,我想计算顺序而不是指定它们手动

我查看了该站点上的几个重新排序示例,但找不到处理观察计数的示例。有办法吗?

library(tidyverse)
library(ggplot2)
data_df <- read_csv("fct, val\na, 12\nb, 12\nc, 2\nb, 14\nc, 4\nc, 6")
data_df <- data_df %>% 
  mutate(fct2 = factor(fct, levels = c("c", "b", "a")))
ggplot(data_df) +
 geom_boxplot(aes(fct2, val)) 

tidyverse 解决方案是使用 forcats 包中的 fct_infreq 函数。

示例:

library(forcats)
library(ggplot2)

ggplot(mtcars, aes(fct_infreq(as.factor(cyl)), mpg)) + geom_boxplot()

# Count of each cylinder type
table(mtcars$cyl)
# 4  6  8 
# 11  7 14