我试图在 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
)
但是,误差线既没有与条对齐(位置 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)
编辑
我的猜测是,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)
关于r - 在ggplot2中将误差线与每组不同数量的条形图对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53962695/