首页 > 解决方案 > 在ggplot2中将误差条与每组不同数量的条对齐

问题描述

我试图在 ggplot2 中的条形图上绘制误差线,每组的条数不同。我想:

这应该是相当标准的,但我正在努力解决错误栏,因为设置似乎并不像文档中position_dodge()的示例那样简单。position_dodge2()geom_crossbar()position_dodge

我最接近的尝试是:

df <- data.frame(
  mean = 2:8,
  loc = c(rep(1, 4), 2, rep(3, 2)),
  # spcs = c(1:4, 1, 1:2),
  spcs = c(1:4, 1, 2, 4)  # Updated on 29 Dec 2018 in response to @Roman Luštrik's comment
)
ggplot(aes(x = factor(loc), y = mean, fill = factor(spcs)), data = df) + 
  geom_col(position = position_dodge2(preserve = "single")) +
  geom_errorbar(
    aes(ymin = mean - 0.2, ymax = mean + 0.2),
    position = position_dodge(width = 0.9),
    width = 0.2
  )

在此处输入图像描述

然而,误差条既没有与条(Locs 3)对齐,也没有像我希望的那样具有相同宽度的晶须(Locs 2 和 3)。

我在这里搜索并发现了一些类似的问题,但不完全是我的情况。因此,我希望能提供一个解决方案,并稍微解释一下我的尝试失败的原因。

附言。我知道如果我facet_grid()通过loc并设置scales = "free_x", space = "free_x"我会得到一个接近的选择,但我不想在这里使用 facet。谢谢!

标签: rggplot2geom-col

解决方案


如果我也将闪避添加到错误栏中,我会得到:

ggplot(aes(x = factor(loc), y = mean, fill = factor(spcs)), data = df) + 
  geom_col(position = position_dodge(preserve = "single")) +
  geom_errorbar(
    aes(ymin = mean - 0.2, ymax = mean + 0.2),
    position = position_dodge(width = 0.9, preserve = "single"),
    width = 0.2)

在此处输入图像描述

编辑

我的猜测是,对于 loc*spcs 因素的组合,一些因素正在下降,但我现在没有足够的动力去检查它。无论如何,解决方法是为缺失因子添加缺失值。

df <- data.frame(mean = 2:8, loc = c(rep(1, 4), 2, rep(3, 2)), spcs = c(1:4, 1, 2, 4))
df <- rbind(df, data.frame(mean = NA, loc = 3, spcs = c(1, 3)))

ggplot(aes(x = factor(loc), y = mean, fill = factor(spcs)), data = df) + 
  geom_col(position = position_dodge(preserve = "single")) +
  geom_errorbar(
    aes(ymin = mean - 0.2, ymax = mean + 0.2),
    position = position_dodge(width = 0.9, preserve = "single"),
    width = 0.2)

在此处输入图像描述


推荐阅读