我能找到的唯一先前问题是this one from 2012,但在我的案例中似乎没有帮助。
我想使用颜色按子组绘制组的平均值。我想在平均值周围显示误差条(置信区间)。我希望误差线的宽度小于默认值。
来自虹膜的数据的示例代码(用于fill
变量的随机数据):
library(ggplot2)
#data
df_sum = structure(list(Species = structure(c(1L, 1L, 2L, 2L, 3L, 3L), .Label = c("setosa",
"versicolor", "virginica"), class = "factor"), fillvar = c("A",
"B", "A", "B", "A", "B"), mean = c(1.43636363636364, 1.48214285714286,
4.16666666666667, 4.34615384615385, 5.49130434782609, 5.6037037037037
), n = c(22, 28, 24, 26, 23, 27), se = c(0.0429161341346969,
0.0281969506722072, 0.103676382414373, 0.0830626768411882, 0.112273142983994,
0.109320809356896), groupvar = structure(c(1L, 1L, 2L, 2L, 3L,
3L), .Label = c("setosa", "versicolor", "virginica"), class = "factor"),
ci_bar = c(2.07961384472768, 2.05183051648029, 2.06865761041905,
2.0595385527533, 2.07387306790403, 2.05552943864287)), .Names = c("Species",
"fillvar", "mean", "n", "se", "groupvar", "ci_bar"), row.names = c(NA,
-6L), class = "data.frame")
ggplot(df_sum, aes(x = groupvar, y = mean, fill = fillvar)) +
geom_bar(stat="identity", position = "dodge") +
geom_errorbar(aes(ymin = mean - ci_bar*se, ymax = mean + ci_bar*se), position = position_dodge(), width = .2) +
xlab("Species") + ylab("Petal.Length")
我们看到了问题。错误栏被躲避,但由于width
设置,它们不会被躲避得足够远。
如果我们在没有width
设置的情况下进行绘图:
ggplot(df_sum, aes(x = groupvar, y = mean, fill = fillvar)) +
geom_bar(stat="identity", position = "dodge") +
geom_errorbar(aes(ymin = mean - ci_bar*se, ymax = mean + ci_bar*se), position = position_dodge()) +
xlab("Species") + ylab("Petal.Length")
这是我们所期望的,但错误条太宽了我的口味。
问题似乎是position_dodge
有一个width
参数,geom_errorbar
也是如此。如果将width=0.2
放入geom_errorbar
,它会转发到position_dodge
,这会导致闪避偏移问题。请注意,如果在width
内设置position_dodge
,则不会将其转发到geom_errorbar
(在外部)。因此,这只会导致偏移关闭,而误差条的宽度不会改变:
ggplot(df_sum, aes(x = groupvar, y = mean, fill = fillvar)) +
geom_bar(stat="identity", position = "dodge") +
geom_errorbar(aes(ymin = mean - ci_bar*se, ymax = mean + ci_bar*se), position = position_dodge(width = .2)) +
xlab("Species") + ylab("Petal.Length")
这与我想要的相反。接下来的问题似乎是如何在width=0.2
内设置geom_errorbar
而不将ggplot2自动转发给position_dodge
。
我只发现了一个轻微的黑客攻击解决方案,即将width
设置为position_dodge
内的默认值(似乎为0.9),以防止它被geom_errorbar
中的值填入{1}}:
ggplot(df_sum, aes(x = groupvar, y = mean, fill = fillvar)) +
geom_bar(stat="identity", position = "dodge") +
geom_errorbar(aes(ymin = mean - ci_bar*se, ymax = mean + ci_bar*se), position = position_dodge(width = .9), width = .2) +
xlab("Species") + ylab("Petal.Length")
这个问题是否有非黑客解决方案?