我必须在 R 的分组条形图中手动给出 SE 值。但是,SE 线与条形的位置不同。我知道我在每个
(x = Species)
中定义的 x 变量导致了这个问题,但我必须定义它,因为我使用多个数据集。这是我的数据:
geom_errorbar
这是条形图的代码:
Datatemp = data.frame( Species = c("Oak", "Oak", "Pine", "Pine","Oak", "Oak", "Pine", "Pine"),
Status = rep(c("Above", "Below"),4),
Sex = c(rep("Male",4), rep("Female",4)),
Value = c(6.86, 7.65, 30.13, 35.71, 7.13, 10.33, 29.24, 31.09),
SE = c(0.7354684, 1.9648560,3.6734597, 4.5276121,
0.7881132, 1.9564864, 3.4784320, 4.243139))
这是输出:
如您所见,误差条分组在中间,如果您能建议一种将它们放置在各自条中的方法,那就太好了。非常感谢!
定义填充美学,
DatatempA = Datatemp %>% filter(Species == "Oak")
DatatempB = Datatemp %>% filter(Species == "Pine")
ggplot() +
geom_bar(data = DatatempB,
mapping = aes(x = Species, y = Value, fill = Status),
stat='identity', position = position_dodge(width = 0.73), width=.67) +
geom_errorbar(data = DatatempB,aes(x = Species, ymin = Value-SE, ymax = Value+SE),
position = position_dodge(.9), width = 0.2) +
scale_fill_manual(name = "Status trees",
labels = c("Above","Below"),
values = c("#7393B3","#0F52BA"),
guide = guide_legend(override.aes = list(fill=c("gray75", "gray25")))) +
new_scale_fill() +
geom_bar(data = DatatempA,
mapping = aes(x = Species, y = Value, fill = Status),
stat='identity', position = position_dodge(width = 0.73), width=.67, show.legend=FALSE) +
geom_errorbar(data = DatatempA, aes(x = Species, ymin = Value-SE, ymax = Value+SE),
position = position_dodge(.9), width = 0.2) +
scale_fill_manual(name = "Status trees",
labels = c("Above","Below"),
values = c("#EADDCA","#F4BB44")) +
facet_grid(Sex ~ .) +
scale_y_continuous(sec.axis = dup_axis(name= "Sex of trees")) +
xlab("Species") +
ylab("Value") +
theme_light() + theme(axis.text.y.right = element_blank(),
axis.ticks.y.right = element_blank(),
axis.ticks.length.y.right = unit(0, "pt"))
SpeciesStatus
SpeciesStatus