1

I've got data refering to financial years, starting from 1 April each year and ending 31 March in next solar year.

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 

Plotting df with library(ggplot2); ggplot(df) + geom_line(aes(date, var)) I get:

enter image description here

Now, what I'm interested in is having say the "2009" label positioned at "2009-04-01", as it's that the actual start of the FY 2009. I managed to get that with the following code:

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

which correctly gives:

enter image description here

My question is (finally :-) ) does some of you have a better way for showing financial years and eventually better codes then the above?

4

1 回答 1

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")
于 2013-04-26T17:12:29.020 回答