我想通过使用 stats_summary
在箱线图组之间添加边际空间方法。
这是我的问题的一个小例子
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”实现视觉分离,并在箱线图组之间添加一个“空间”(我限制使用
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))
前后
关于r - 如何在嵌套箱线图中添加中间空间ggplot2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30889674/