r - R:在每年一月初添加一条垂直线
问题描述
从 2015 年到现在的工作日(不包括周六、周日),我在数据框中有一个每日系列:
df <- df[, c("Date","y")]
我可以绘制图表:
情节(df$日期,df$y,类型=“l”)
我还可以绘制垂直线:
abline (v= x)
但是我怎样才能为系列中每年 1 月的第一个日期绘制一条垂直线(这可能与 1 月 1 日不同)。
谢谢您的帮助。
解决方案
您几乎拥有它,您只需要一种方法来确定所有第一个 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])
结果:
推荐阅读
- visual-studio-code - Discord 机器人播放音乐
- react-native - 当我想将设备中的文件发送到我的服务器时,RNFS.upload 出现意外的流结束错误
- javascript - OpenLayers 在运行时改变特征的颜色
- anylogic - 叉车停止移动并冻结在原地
- java - java中的泛型表达式
- c# - 我可以将方法标识符(例如:MyClass.MyMethod)作为 C# 中的方法参数吗?
- android - 错误 java.lang.illegalstateexception 请求 == null
- spring-batch - 暂停spring boot rabbit mq consumer的最简单方法是什么?
- c++ - Googletest (gtest) / googlemock (gmock):为什么“interleav[ing] `EXPECT_CALL()`s and calls to the mock functions”未定义行为?
- python - 将python行值与以前的(重复)进行比较