r - 在ggplot2中将误差线与每组不同数量的条形图对齐

标签 r ggplot2 geom-col

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

  • 固定条形宽度,无论每组的条形数量如何
  • 具有相同 mustache 宽度的误差线,与相应的条对齐

这应该是相当标准的,但我正在努力解决误差线,因为 position_dodge()position_dodge2() 中的设置似乎并不那么直接-forward 作为 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
  )

enter image description here

但是,误差线既没有与条对齐(位置 3),也没有像我希望的那样具有相同的晶须宽度(位置 2 和 3)。

我用谷歌搜索并发现了一些类似的问题,但不完全是我的情况。因此,我希望有一个解决方案,并对我的尝试失败的原因进行一些解释。

ps。我知道如果我 facet_grid() by loc 并设置 scales = "free_x", space = "free_x" 我会得到一个接近的替代方案,但我不想在这里使用方面。谢谢!

最佳答案

如果我也向错误栏添加闪避,我会得到以下结果:

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)

enter image description here

编辑

我的猜测是,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)

enter image description here

关于r - 在ggplot2中将误差线与每组不同数量的条形图对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53962695/

相关文章:

r - 使用 geom_smooth 强制拦截

r - 使用 ggplot2 facet_wrap 在地理点上绘制图形

r - 如何删除geom_col周围的ggplot2背景和裁剪边距

r - 使用 ggplot 和 gtable 对齐多个图

r - knitr:在循环中调用 ggplot2 函数在伴随某些其他绘图函数时不会绘图

r - 在 ggplot 中,我不想标记值为零的 geom_col 条,而只标记具有值的条(它们都是正数)

r - 如何绘制一个因子水平作为 geom_col/geom_area 的基础

r - 拆分矩阵并重新加入

将列重命名为 Y X1 X2 X3 X4 .. XN

r - 在 R 中使用 igraph 从数据框中添加边权重