【问题标题】:R: plot adding a vertical line at the beginning of each JanuaryR:在每年一月初添加一条垂直线
【发布时间】:2020-01-14 19:05:03
【问题描述】:

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

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

我可以绘制图表:

绘图(df$Date,df$y, type="l")

我也可以画垂直线:

斜线 (v= x)

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

感谢您的帮助。

【问题讨论】:

  • 请展示一个可重现的小例子

标签: r


【解决方案1】:

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

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

结果:

【讨论】:

  • 非常感谢。