r - 如何在嵌套箱线图中添加中间空间ggplot2

标签 r ggplot2 boxplot

我想通过使用 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))

结果是下图。
boxplots

我想为每个“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))

前后

enter image description here

关于r - 如何在嵌套箱线图中添加中间空间ggplot2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30889674/

相关文章:

r - 通过垂直分割垃圾箱,通过精确的截止点为 ggplot 直方图着色

r - 箱线图 - 查找上下晶须的值

r - 117/12/31 格式的日期

c - 将数组从 C 传递给 Rust,尺寸在运行时定义

r - 在 R 或 Excel 中计算多行中不同定性值的数量

python - 从 Pandas 时间序列生成星期几箱线图的最佳方法

r - 更改R中箱线图中各个框的宽度

r - 熔化和 reshape 具有相似列根词的列

r - 在 ggplot2 中使用颜色转换时,更改图例渐变而不是图例中断位置

r - 具有交叉分类组的ggplot中的箱线图宽度