如何在嵌套箱线图ggplot2中添加中间space

How to add inbetween space in nested boxplots ggplot2

我想使用 stats_summary 方法在各组箱线图之间添加边缘 space。

这是我的问题的一个小例子

library(ggplot2)
library(reshape2)
data1 <- (lapply(letters[1:5], function(l1) return(matrix(rt(5*3, 1), nrow = 5, ncol = 3, dimnames = list(cat2=letters[6:10], cat3=letters[11:13])))))
names(data1) <- letters[1:5]
data2 <- melt(data1)

customstats <- function(x) {
  xs <- sort(x)
  return(c(ymin=min(x), lower= mean(xs[xs < mean(x)]), middle = mean(x) , upper = mean(xs[xs > mean(x)]), ymax=max(x)))
}

ggplot(data2, aes(x=cat2, y=value, fill=cat3), width=2) + 
  stat_summary(fun.data = customstats, geom = "boxplot", 
    alpha = 0.5, position = position_dodge(1), mapping = aes(fill=cat3))

结果如下图。

我想为每个 "cat2" 实现视觉分离,并在箱线图组之间添加一个 "space"(我只能使用 stats_summary,因为我有自定义统计)。我该怎么做?

我以丑陋(但对我有效)的方式解决了一个类似的问题,方法是创建一个数据框,该数据框具有与我的原始数据相同的绘图变量,但 x(或 y)定位或分解为适合两点我想分开并缺少 y(或 x)的值。对于您的问题,我添加了以下代码并获得了一个具有集群空间分离的图像。

library(plyr)

empties <- data.frame(cat2_orig=unique(data2$cat2)[-length(unique(data2$cat2))])
#no extra space needed between last cluster and edge of plot
empties$cat2 <- paste0(empties$cat2_orig,empties$cat2_orig)
empties$value <- NA


data2_space <- rbind.fill(data2,empties)

ggplot(data2_space, aes(x=cat2, y=value, fill=cat3), width=2) + 
  stat_summary(fun.data = customstats, geom = "boxplot", 
           alpha = 0.5, position = position_dodge(1), mapping =     aes(fill=cat3)) +
#remove tickmarks for non-interesting points on x-axis
  scale_x_discrete(breaks=unique(data2$cat2))

前后