R:如何按方差对箱线图进行排序?

R: How to order boxplots by variance?

是否可以按方差对 R 中的箱线图进行排序?

rm(list = ls())
library(datasets)
library(ggplot2)

data(airquality)
airquality$Month <- factor(airquality$Month,
                           labels = c("May", "Jun", "Jul", "Aug", "Sep"))


p10 <- ggplot(airquality, aes(x = Month, y = Ozone)) +
        geom_boxplot()
p10

如何才能使变化最大的变量位于该图的左侧?

如有任何帮助,我们将不胜感激!

使用 reorder 你可以做:

library(ggplot2)

data(airquality)
airquality$Month <- factor(airquality$Month,
                           labels = c("May", "Jun", "Jul", "Aug", "Sep"))


ggplot(airquality, aes(x = reorder(Month, Ozone, function(x) -var(x, na.rm = TRUE)), y = Ozone)) +
  geom_boxplot()
#> Warning: Removed 37 rows containing non-finite values (stat_boxplot).

这是一个完整的 tidyverse-based reprex

library(tidyverse)

airquality %>%
  group_by(Month) %>%
  mutate(var = var(Ozone, na.rm = TRUE)) %>%
  ungroup() %>%
  mutate(Month = fct_reorder(month.abb[Month], -var)) %>%
  ggplot(aes(x = Month, y = Ozone)) +
  geom_boxplot()
#> Warning: Removed 37 rows containing non-finite values (stat_boxplot).

reprex package (v2.0.1)

于 2022-04-18 创建