boshek boshek - 8 months ago 59
R Question

Plotting a non-standard year (water year) with ggplot2

Building on this question and the use of "water year" in R I have question regarding plotting in ggplot2 with a common date axis over many years. A water year is definitely the start of the year to be October 1st ending September 30. It is a little more sensible for the hydrological cycle.

So say I have this data set:


df <- data.frame(Date=seq.Date(as.Date("1910/1/1"), as.Date("1915/1/1"), "days"),

Then here is the wtr_yr function:

wtr_yr <- function(dates, start_month=10) {
# Convert dates into POSIXlt
dates.posix = as.POSIXlt(dates)
# Year offset
offset = ifelse(dates.posix$mon >= start_month - 1, 1, 0)
# Water year
adj.year = dates.posix$year + 1900 + offset
# Return the water year

What I would like to do is use colour as a grouping variable, then make a x axes that only consists of month and date information. Usually I've done like so (using the lubridate package):


This works fine if year is arranged normally. However in this water year scenario, the real year span the water year. So ideally I'd like a plot that goes from October 1 to September 30 and plot separate lines for each water year maintaining all the correct water years. Here is where I am so far:

df1 <- df %>%
mutate(wtr_yrVAR=factor(wtr_yr(Date))) %>%

df1 <- %>%
ggplot(aes(x=CDate, y=y, colour=wtr_yrVAR)) +

So plotting that obviously date spans from Jan to Dec. Any ideas how I can force ggplot2 to plot these along the water year lines?


Here is a method that works:

df3 <- df %>%
  mutate(wtr_yrVAR=factor(wtr_yr(Date))) %>%
  #seq along dates starting with the beginning of your water year
  mutate(CDate=as.Date(paste0(ifelse(month(Date) < 10, "1901", "1900"),
                              "-", month(Date), "-", day(Date))))


df3 %>%
  ggplot(., aes(x = CDate, y = y, colour = wtr_yrVAR)) +
  geom_point() +
  scale_x_date(date_labels = "%b %d")

Which gives:

enter image description here