2016-01-29 84 views
1

我一直在嘗試在我的一塊地塊上顯示誤差線,並且差不多都得到了它。除了兩個錯誤條不出現的情況之外,我可以正確顯示錯誤條。這裏是我的代碼:如何修復geom_errorbar輸出錯誤?

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

問題是您的錯誤欄超出了用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