【问题标题】:How to add inbetween space in nested boxplots ggplot2如何在嵌套箱线图ggplot2中添加中间空间
【发布时间】:2015-06-17 11:02:10
【问题描述】:

我想使用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)。我该怎么做?

【问题讨论】:

  • 可能最安全的选择是在手动预计算数据上使用geom_bar。实际上,这是我看到的唯一可能的方法。
  • 不理想,但您可以使用构面:+ facet_grid(.~cat2, scales = "free_x")
  • 这可以在一张图上工作,是的。在我的特殊情况下(不在示例中),我已经有一个基于附加变量的 facet_grid,因此无法使用您的解决方案。

标签: r ggplot2 boxplot


【解决方案1】:

我以一种丑陋(但对我有效)的方式解决了一个类似的问题,方法是创建一个与我的原始数据具有相同绘图变量的数据框,但将 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))

之前和之后

【讨论】:

  • 谢谢,它似乎有效,但我不明白为什么。不幸的是不适用于我的实际数据,但我会尝试调整该技术。
  • 不客气!它之所以有效,是因为它创建了额外的因子水平并绘制了它们(但没有什么可绘制的 --> 空白空间)。然后 scale_x_discrete 仅将刻度和标签添加到原始因子水平。如果您有实际数据的示例,我愿意看一下以适应它。
  • 再次感谢。我遇到的问题是该图由面集组成,并且它显示了 NA x NA 空面。解决方案是 expand.grid(unique(facet1), unique(facet2), additional_empty_factors) 和 then 将它们绑定到 data_space。那行得通。
  • 很高兴知道!你对间距满意吗?我也有这方面的技巧,但它变得更加丑陋。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-14
  • 1970-01-01
  • 1970-01-01
  • 2020-11-08
  • 2022-12-22
  • 1970-01-01
相关资源
最近更新 更多