如何修复geom_errorbar输出错误?

时间:2016-01-29 18:47:48

标签: r ggplot2

我一直在尝试在我的一个地块上显示错误条并几乎得到它。除了没有出现两个错误条的事实之外,我可以正确显示错误条。这是我的代码:

    adat <- data.frame(1:8)
names(adat)[1] <- "Technology"
adat$Technology <- c("1","1","1","1","2","2","2","2")
adat$Behaviors <- c("Low Moisture","High Moisture","Low Density","High Density","Low Moisture","High Moisture","Low Density","High Density")
adat$Average.duration <- c(374,347,270,313,273,280,242,285)
adat$sd <- c(207,107,120,920,52,61,50,84)

limits <- aes(ymin = adat$Average.duration - adat$sd, ymax = adat$Average.duration + adat$sd)

ggplot(adat, aes(x = Behaviors, y = Average.duration, fill = Technology)) +
  geom_bar(stat = "identity", position = "dodge") + 
  ylim(0,500) +
  geom_errorbar(limits, position = position_dodge(.9), width = .75)

当我运行上面的代码时,我得到以下输出: enter image description here

我不知道为什么两个错误栏没有显示出来。有什么建议吗?

1 个答案:

答案 0 :(得分:1)

问题是您的错误栏超出了您使用ylim()设置的限制。尝试使用此绘图:

limits <- aes(ymin = Average.duration - sd, ymax = Average.duration + sd)

ggplot(adat, aes(x = Behaviors, y = Average.duration, fill = Technology)) +
  geom_bar(stat = "identity", position = "dodge") + 
  geom_errorbar(limits, position = "dodge")

First Plot

另外,请注意,您无需向adat$...电话提供limits 因为您将在ggplot()的电话中“设置”。

ylim()scale_y_continuous()将取消范围之外的数据点。如果您仍希望在0 to 500 y范围内进行绘制,则需要使用coord_cartesian()

ggplot(adat, aes(x = Behaviors, y = Average.duration, fill = Technology)) +
  geom_bar(stat = "identity", position = "dodge") + 
  geom_errorbar(limits, position = "dodge") +
  coord_cartesian(ylim = c(0, 500))

Plot With Coord_Cartesian