格式化ggplot中的日期以突出显示财务年度的开始

时间:2013-04-26 16:38:46

标签: r datetime ggplot2

我从每年的4月1日开始到下一个太阳年的3月31日结束了有关财政年度的数据。

df <- data.frame(date = seq(as.POSIXct("2008-04-01"), by="month", length.out=49),
                 var  = rnorm(49))

head(df,3)
        date         var
1 2008-04-01  0.04265025
2 2008-05-01 -1.59671801
3 2008-06-01  0.4909673 

使用df绘制library(ggplot2); ggplot(df) + geom_line(aes(date, var))我得到:

enter image description here

现在,我感兴趣的是说&#34; 2009&#34;标签位于&#34; 2009-04-01&#34;,因为它是2009财年的实际开始。我设法通过以下代码得到了它:

ggplot(df) + geom_line(aes(date, var)) +
  scale_x_datetime(breaks = df$date[months(df$date)=="April"],
                   labels = date_format("%Y"))

正确地给出了:

enter image description here

我的问题是(最后:-))你们中的一些人是否有更好的方式来展示财政年度,最终更好的代码呢?

1 个答案:

答案 0 :(得分:3)

您可以使用geom_rect来突出显示财务年度。假设您将原始图表保存为p,请尝试:

bgdf <- data.frame(xmin=as.POSIXct(paste0(2008:2011,"-04-01")),
                   xmax=as.POSIXct(paste0(2009:2012,"-04-01")),
                   ymin=min(df$var),ymax=max(df$var),alpha=((2008:2011)%%2)*0.1)
p + geom_rect(aes(xmin=xmin,xmax=xmax,ymin=ymin,ymax=ymax),
              data=bgdf,alpha=bgdf$alpha,fill="blue")