使用ggplot2在R中为Date设置geom_errorbar

时间:2015-11-29 10:38:02

标签: r ggplot2 errorbar

在许多情况下,我们需要证明标准错误。在ggplot2中,我们可以使用geom_errorbar函数执行此操作。我发现当x变量是Date类型时,ggplot2无法完全绘制错误栏。有关详细信息,请参阅下面的R脚本。

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

1 个答案:

答案 0 :(得分: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)))