使用 ggplot2 为 R 中的日期绘制 geom_errorbar

Using ggplot2 to plot geom_errorbar for Date in R

在很多情况下,我们需要证明标准误差。在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

只需遵循 RHA's (下面的代码)。 @RHA,请随时将我的答案复制到一个新的答案中,因为它更多的是你的而不是我的。

# 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)))