首页 > 解决方案 > R:在每年一月初添加一条垂直线

问题描述

从 2015 年到现在的工作日(不包括周六、周日),我在数据框中有一个每日系列:

df <- df[, c("Date","y")] 

我可以绘制图表:

情节(df$日期,df$y,类型=“l”)

我还可以绘制垂直线:

abline (v= x)

但是我怎样才能为系列中每年 1 月的第一个日期绘制一条垂直线(这可能与 1 月 1 日不同)。

谢谢您的帮助。

标签: r

解决方案


您几乎拥有它,您只需要一种方法来确定所有第一个 1 月的日期,然后传递这些日期的向量,x

abline(v=x)

lubridate 和 dplyr 提供了很好的方法来解决这个问题。

# fake data: a sample of dates (in order) and a cumulative series
set.seed(123)
n <- 200
dat <- data.frame(
  Date = sort(sample(seq(from=as.Date('2015-01-01'), 
                         to=as.Date('2018-01-01'), 
                         by='day'),
                     n)
              ),
  y = cumsum(runif(n, min = -10, max=10)))

# load libraries and add flag for first jan dates
library(dplyr)
library(lubridate)

dat <- dat %>%
  # ensure it's sorted by date
  arrange(Date) %>%
  # group by year and month
  group_by(yr = year(Date), mth = month(Date)) %>%
  # flag each first January row
  mutate(first_jan_row = mth ==1 & row_number()==1)

现在您可以绘制它们:

# your plot
plot(dat$Date, dat$y, type='l')
# ablines on all first jan dates
abline(v=dat$Date[dat$first_jan_row])

结果:

在此处输入图像描述


推荐阅读