首页 > 解决方案 > 如何手动增加R中分组箱形图中两个特定框之间的间距?

问题描述

有没有办法增加这个盒子图中黄色和红色盒子之间的间距?

set.seed(40)
df <- data.frame(
  Outcome = runif(60), 
  Fruit = rep(1:3, each = 10), 
  Freshness = rep(c(0, 0.5), each = 30), 
  Farm = factor(rep(c("A", "B"), each = 5))
) %>% 
  transform(
  Outcome = Outcome*Fruit+Freshness, 
  Fruit = as.factor(Fruit), 
  Freshness = as.factor(Freshness)
)

ggplot(data = df, aes(Farm, Outcome, col = Freshness, fill = Fruit)) + 
  geom_boxplot() + 
  scale_color_manual(values = c("lightslategrey", "black"), labels = c("Stale", "Fresh")) + 
  scale_fill_manual(values = c("red", "orange", "yellow"), labels = c("Apples", "Oranges", "Bananas"))

在此处输入图像描述

我想增加每个“农场”组中“新鲜度”颜色组之间的间距(或放置一个间隙),但不要太多,以至于盒子会像“农场”组那样分开。也就是说,我只想增加黄色和红色框之间的间距,以强调“新鲜度”组之间的区别。

“水果”组仍将保持组内盒子之间的距离。也就是说,相邻的红色、橙色和黄色框将保持靠近。

标签: rggplot2groupingboxplotspacing

解决方案


您可以通过添加并使用宽度选择来修改框之间的间距,直到满意position=position_dodge(width =...))为止。geom_boxplot()

ggplot(data = df, aes(Farm, Outcome, col = Freshness, fill = Fruit)) + 
  geom_boxplot(position=position_dodge(width = 1)) + 
  scale_color_manual(values = c("lightslategrey", "black"), labels = c("Stale", "Fresh")) + 
  scale_fill_manual(values = c("red", "orange", "yellow"), labels = c("Apples", "Oranges", "Bananas"))

这里是原作对比。 在此处输入图像描述 而修改后的 (with width=1) 在此处输入图像描述 增加 X 轴上类别之间的间距是一个不同的问题,也是一个更难解决的问题。一种简单的解决方法是在 X 轴上使用具有自由比例的刻面。

ggplot(data = df, aes(Farm, Outcome, col = Freshness, fill = Fruit)) + 
    geom_boxplot(position=position_dodge(width = 1)) + 
    scale_color_manual(values = c("lightslategrey", "black"), labels = c("Stale", "Fresh")) + 
    scale_fill_manual(values = c("red", "orange", "yellow"), labels = c("Apples", "Oranges", "Bananas")) +
    facet_wrap(~Farm, ncol = 2, scales = "free_x")

在此处输入图像描述


推荐阅读