【问题标题】:Plotting a non-standard year (water year) with ggplot2用 ggplot2 绘制非标准年份(水年)
【发布时间】:2016-10-31 22:58:33
【问题描述】:

在此question 和 R 中使用“水年”的基础上,我对多年来使用共同日期轴在 ggplot2 中绘图有疑问。水年绝对是一年的开始,从 10 月 1 日到 9 月 30 日结束。它对水文循环更有意义。

假设我有这个数据集:

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
}

我想做的是使用颜色作为分组变量,然后制作一个仅包含月份和日期信息的 x 轴。通常我是这样做的(使用 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()

因此,显然日期跨度从 1 月到 12 月。有什么想法可以强制 ggplot2 沿着水年线绘制这些吗?

【问题讨论】:

  • 您的示例不可重现。它在调用 ggplot2 时引发错误。

标签: r ggplot2


【解决方案1】:

这是一个有效的方法:

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

这给出了:

【讨论】:

    【解决方案2】:

    不是很优雅,但这应该可以:

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

    【讨论】:

      猜你喜欢
      • 2017-12-14
      • 1970-01-01
      • 1970-01-01
      • 2020-12-09
      • 2019-12-04
      • 2017-06-21
      • 1970-01-01
      • 2019-07-07
      • 1970-01-01
      相关资源
      最近更新 更多