2016-10-31 33 views
1

基于此question和在R中使用“water year”我有关于在ggplot2中绘制多年的共同日期轴的问题。水年肯定是今年的开始,即10月1日结束的9月30日。这对水文循环来说更为明智。用ggplot2绘制非标准年(水年)

所以说我有这组数据:

library(dplyr) 
library(ggplot2) 
library(lubridate) 

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

然后这里是wtr_yr功能:

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 
    adj.year 
} 

我想要做的就是使用颜色作为分组变量,然后使斧仅包含月份和日期信息的轴。通常我这样做(使用lubridate包):

ymd(paste0("1900","-",month(df$Date),"-",day(df$Date))) 

这工作正常,如果年正常安排。然而在这个水年的情况下,实际的年份跨越了水年。因此,理想情况下,我想要一个从10月1日到9月30日的情节,并为每个水年划分单独的行,保持所有正确的水年。这里是我到目前为止:

df1 <- df %>% 
    mutate(wtr_yrVAR=factor(wtr_yr(Date))) %>% 
    mutate(CDate=as.Date(paste0("1900","-",month(Date),"-",day(Date)))) 

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

所以策划这显然日期跨度从一月到十二月的任何想法如何,我可以强制GGPLOT2沿水年线描绘出这些?

+0

您的示例不可重现。它在调用ggplot2时会抛出一个错误。 – Zach

回答

3

这是一个可行的方法:其中给出

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

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

然后

enter image description here

0

不是很优雅,但是这应该工作:

df1 <- df %>% 
    mutate(wtr_yrVAR=factor(wtr_yr(Date))) %>% 
    mutate(CDdate= as.Date(as.numeric(Date - as.Date(paste0(wtr_yrVAR,"-10-01"))), origin = "1900-10-01")) 

df1 %>% ggplot(aes(x =CDdate, y=y, colour=wtr_yrVAR)) + 
    geom_line() + theme_bw()+scale_x_date(date_breaks = "1 month", date_labels = "%b", limits = c(as.Date("1899-09-30"),as.Date("1900-10-01")))+theme_bw()