【发布时间】: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 时引发错误。