如何在嵌套的boxplots ggplot2中添加空格

时间:2015-06-17 11:02:10

标签: r ggplot2 boxplot

我想使用Robot robot = new Robot(); // A short pause, just to be sure that OK is selected Thread.sleep(3000); robot.keyPress(KeyEvent.VK_ENTER); 方法在箱形图组之间添加边距。

以下是我的问题的一个小例子

stats_summary

结果如下图。 boxplots

我想为每个“cat2”实现视觉分离,并在箱形图组之间添加“空格”(因为我有自定义统计信息,所以我已经限制使用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)) 了)。我该怎么办?

1 个答案:

答案 0 :(得分:3)

我已经通过创建一个与我的原始数据具有相同绘图变量的数据帧来解决一个丑陋(但对我来说有效)的类似问题,但是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))

之前&amp;之后

enter image description here