如何将ggplot2 boxplots分为不同的组(不是通常的boxplots分组)?

时间:2019-05-12 23:50:04

标签: r ggplot2 boxplot

假设我有5个箱型图,例如5月至9月的臭氧水平。

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

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

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

现在,我想在视觉上将它们分组,例如2 + 1 + 2:所以我想在6月和7月之间以及7月和8月之间留一个间隔。 (实际分组可能会有所不同。)

用于对箱形图进行分组的常用方法似乎无法解决此问题。

2 个答案:

答案 0 :(得分:3)

您可以创建一个将x变量分组的变量-该方法取决于您的数据,但是forcats::fct_collapse是执行此操作的一种简单方法。然后用它来刻画情节。借助facet_grid,您可以设置自由的x缩放比例和自由的间距,以便根据每个面板具有多少个箱形图来调整面板的大小。

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

air_groups <- airquality %>%
  mutate(group = forcats::fct_collapse(Month, 
                              "group 1" = c("May", "Jun"),
                              "group 2" = c("Jul"),
                              "group 3" = c("Aug", "Sep")))
ggplot(air_groups, aes(x = Month, y = Ozone, fill = Month)) +
  geom_boxplot() +
  facet_grid(cols = vars(group), scales = "free_x", space = "free")

如果您想掩盖您使用构面的事实,或者这些组本身并没有实际意义,则可以删除构面标签。还有其他主题参数可以在这里进行实验,例如面板之间的间距。

ggplot(air_groups, aes(x = Month, y = Ozone, fill = Month)) +
  geom_boxplot() +
  facet_grid(cols = vars(group), scales = "free_x", space = "free") +
  theme(strip.text = element_blank())
#> Warning: Removed 37 rows containing non-finite values (stat_boxplot).

答案 1 :(得分:1)

这可能是作弊行为,但我不太确定您对x轴上的标签有多大兴趣。

library (dplyr) # for case_when()
special_x <- case_when(airquality$Month == "May" ~ 1,
              airquality$Month == "Jun" ~ 2,
              airquality$Month == "Jul" ~ 4,
              airquality$Month == "Aug" ~ 6,
              airquality$Month == "Sep" ~ 7)

    airquality$special_x <- special_x

    ggplot(airquality, aes(x = special_x, y = Ozone, fill = Month)) +
      geom_boxplot()

此外,您可以添加+ labs(x="") + theme(axis.text.x = element_blank(), axis.ticks.x = element_blank())

更新

如评论所述,

ggplot(airquality, aes(x = special_x, y = Ozone, fill = Month)) +
  geom_boxplot()+
  scale_x_continuous(breaks = c(1,2,4,6,7),
                     labels =c("May", "Jun", "Jul", "Aug", "Sep"))+
  labs(x="")

会产生

enter image description here