2015-11-29 45 views
1

在很多情況下,我們需要演示標準錯誤。在ggplot2中,我們可以使用geom_errorbar函數來完成。我發現,當x變量是Date類型時,ggplot2不能完全繪製錯誤欄。有關更多信息,請參閱下面的R腳本。使用ggplot2在R中繪製日期的geom_errorbar

library(gcookbook) # For the data set 
# Take a subset of the cabbage_exp data for this example 
ce <- subset(cabbage_exp, Cultivar == "c39") 
# With a line graph 

p1 = ggplot(ce, aes(x=Date, y=Weight)) + 
    geom_line(aes(group=1)) + 
    geom_point(size=4) + 
    geom_errorbar(aes(ymin=Weight-se, ymax=Weight+se), width=.2) 

ce$Date = as.Date(c('01/01/2001', '01/01/2002', '01/01/2003'), "%m/%d/%Y") 

p2 = ggplot(ce, aes(x=Date, y=Weight)) + 
    geom_line(aes(group=1)) + 
    geom_point(size=4) + 
    geom_errorbar(aes(ymin=Weight-se, ymax=Weight+se), width=.2) 

p1 
p2 

enter image description here

+5

我仍然看到errorbars,只在最後水平線丟失。那是因爲一天的寬度很小才能看到。試試'width = 10' – RHA

+1

@RHA是對的。要獲得相同的錯誤條寬度(數據點之間距離的20% - 如果等距分佈),請嘗試:'width = .2 *((max(ce $ Date)-min(ce $ Date))/ length CE $日期)' –

回答

1

只需以下RHAdirections(下面的代碼)。 @RHA,請隨意將我的答案複製到新的答案中,因爲它更適合你,那麼它就是我的答案。

geom_errorbar of width

# install.packages("gcookbook", dependencies = TRUE) 
library(gcookbook) # For the data set 
# Take a subset of the cabbage_exp data for this example 
ce <- subset(cabbage_exp, Cultivar == "c39") 
# With a line graph 

# install.packages("ggplot2", dependencies = TRUE) 
require(ggplot2) 

ce$Date = as.Date(c('01/01/2001', '01/01/2002', '01/01/2003'), "%m/%d/%Y") 

(p2 = ggplot(ce, aes(x=Date, y=Weight)) + 
    geom_line(aes(group=1)) + 
    geom_point(size=4) + 
    geom_errorbar(aes(ymin = Weight- se, ymax= Weight + se), width=45)))