【发布时间】:2016-10-07 11:47:44
【问题描述】:
我想在 R 中创建一个时间序列图表,将今年与去年进行比较。我想用今年的日期作为我的 x 轴。
给定一组 2 年或更长时间的日期,使它们成为同一年的函数是什么?
数据示例:
mydata <- data.frame(
date.col = as.Date(c('2014-05-23', '2014-05-24', '2014-05-25', '2015-05-23', '2015-05-24', '2015-05-25', '2016-05-23', '2016-05-24', '2016-05-25')),
value = c(10,23,15,13,26,17,22,30,19))
date.col value
1 2014-05-23 10
2 2014-05-24 23
3 2014-05-25 15
4 2015-05-23 13
5 2015-05-24 26
6 2015-05-25 17
7 2016-05-23 22
8 2016-05-24 30
9 2016-05-25 19
预期输出:
date.col value adj.date
1 2014-05-23 10 2016-05-23
2 2014-05-24 23 2016-05-24
3 2014-05-25 15 2016-05-25
4 2015-05-23 13 2016-05-23
5 2015-05-24 26 2016-05-24
6 2015-05-25 17 2016-05-25
7 2016-05-23 22 2016-05-23
8 2016-05-24 30 2016-05-24
9 2016-05-25 19 2016-05-25
理想情况下,该函数可以轻松放入 dplyr 链中:
mydata %>% normalize.dates(date.col, fit.to='2016') %>% ggplot(...)
【问题讨论】:
-
format(x,"%j")会将所有内容转换为儒略,然后您可以绘制它并根据儒略日定位添加 x 轴。或者甚至将朱利安日期放在底部。闰年让事情变得有趣。否则你的解决方案应该没问题。
标签: r ggplot2 time-series dplyr timeserieschart