在多面箱线图之间增加 space

Increasing space between faceted boxplots

我正在用 ggplot2 制作多面盒。我想均匀地增加每个方面的箱线图之间的垂直 spaces,这样我就可以在那些 spaces 中包含一些文本,但到目前为止我还没能做到。

我使用了函数 position_dodge() 并增加了宽度,如这里所建议的:,但情节保持不变,没有任何变化。下面是一段代码,可让您重现该问题:

library(ggplot2)

set.seed(2)
bp_data <- data.frame(Result=runif(100, min=0, max=2),
                  Method=rep(c("s1", "s2", "s3", "s4"), 25),
                  Var=rep(c("v1", "v2", "v3", "v4", "v5"), 20),
                  stringsAsFactors=FALSE)

bp <- ggplot(bp_data) + 
  aes(x = Method, y = Result) +
  geom_boxplot(width=0.7, position=position_dodge(width=5.0)) +
  coord_flip() +
  facet_grid(Var ~ .)
bp

为函数 position_dodgewidth 参数设置不同的值没有任何效果。

请注意,我想要做的是增加每个方面内箱线图之间的 space,而不是增加方面之间的 space。

一种解决方法是将您的方法转换为数值变量,然后增加数值:

bp_data$Method_num <- as.integer(factor(bp_data$Method))
bp_data$Method_num <- 1.5 * bp_data$Method_num

bp <- ggplot(bp_data) + 
  aes(x = Method_num, y = Result, group = Method) +
  geom_boxplot(width=0.7, position=position_dodge(width=5.0)) +
  coord_flip() +
  facet_grid(Var ~ .) +
  scale_x_continuous(breaks = unique(bp_data$Method_num), 
                     labels = unique(bp_data$Method)) +
  theme(panel.grid.minor.y = element_blank())
bp