【问题标题】:How to set specific date as the beginning date of the year如何将特定日期设置为一年的开始日期
【发布时间】:2020-11-26 19:05:23
【问题描述】:

我想使用流量数据绘制年均值 WATER YEAR,从 10 月开始,到 9 月结束(比如 10/01/1983 到 09/30/1984,这被定义为 1984 年的水年) 我试图在别处寻找解决方案,但失败了。

现在我正在使用以下脚本来绘制年平均流量

library(tidyverse)
library(lubridate)
library(ggplot2)

#df <- read_csv('dataframe.csv')

df <- df %>% 
  mutate(date = mdy(df$date))

df <- df %>%
  mutate(year = floor_date(date, "year")) %>%
  group_by(year) %>%
  summarize(avg = mean(flow)) 


y <- df$avg
x <- as.Date(df$year, format = "Y")
d <- data.frame(x = x, y = y)

# interpolate values from zero to y and create corresponding number of x values
vals <- lapply(d$y, function(y) seq(0, y, by = 0.1))
y <- unlist(vals)
mid <- rep(d$x, lengths(vals))
d2 <- data.frame(x = mid - 100,
                 xend = mid + 100,
                 y = y,
                 yend = y)

ggplot(data = d2, aes(x = x, xend = xend, y = y, yend = yend, color = y)) +
  geom_segment(size = 2) +
  scale_color_gradient2(low = "midnightblue", mid = "deepskyblue", high = "aquamarine", 
                        midpoint = max(d2$y)/2)+
  scale_x_date(date_breaks = "1 year",date_labels = "%Y", expand = c(0,0)) +
  theme(axis.text.x = element_text(angle=90, vjust=.5))+
  labs(x = "Years", y = "Mean Annual Flow (cms)")+
  ggtitle("Mean Annual Flow, Rancho River at ELdorado (1983-2020)")+
  theme(plot.title = element_text(hjust = 0.5))

为此,我使用日历年得到了以下结果

如果我使用水年,1983 年将没有结果

数据框可以在以下链接中找到

https://drive.google.com/file/d/11PVub9avzMFhUz02cHfceGh9DrlVQDbD/view?usp=sharing

请提供帮助。

【问题讨论】:

    标签: r ggplot2 tidyverse lubridate


    【解决方案1】:

    如果date优于10/01/year(date),则表示这是下一年(水年):

    df %>%
     mutate(date=mdy(date), year=year(date), year = year + (date >= mdy(paste0("10/01/", year))))
    
    # A tibble: 5,058 x 3
       date        flow  year
       <date>     <dbl> <dbl>
     1 1983-10-01  3.31  1984
     2 1983-10-02  3.19  1984
     3 1983-10-03  3.7   1984
     4 1983-10-04  3.83  1984
     5 1983-10-05  3.44  1984
     6 1983-10-06  4.37  1984
     7 1983-10-07  6.78  1984
     8 1983-10-08  6.3   1984
     9 1983-10-09  6.46  1984
    10 1983-10-10  6.62  1984
    # … with 5,048 more rows
    

    【讨论】:

    • 您能告诉我您是如何将解决方案集成到原始脚本中的吗? @Abdessabour Mtk
    • @Rancho 带有更新版本的答案,您无需更改任何内容
    • @Rancho 好的,我会的
    猜你喜欢
    • 2019-11-20
    • 2019-01-06
    • 1970-01-01
    • 1970-01-01
    • 2015-03-06
    • 2023-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多