【问题标题】:r - map dates from multiple years to a single yearr - 将日期从多年映射到一年
【发布时间】: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


【解决方案1】:

这很好用:

as.Date(format(date.col, '2016-%m-%d'))

适合 dplyr 链:

my.data %>% mutate(adj.date = as.Date(format(date.col, '2016-%m-%d'))) %>%
    ggplot(aes(x=adj.date)) + ...

当所有日期都需要归一化以进行年度比较时,对于时间序列图很有用:

mydata %>%
    mutate(adj.date = as.Date(format(date.col, '2016-%m-%d'))) %>%
    ggplot(aes(x=adj.date, y=value, color=as.factor(year(date.col)))) + geom_line()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-27
    • 2019-03-03
    • 2021-06-23
    • 1970-01-01
    • 1970-01-01
    • 2021-10-08
    • 2012-01-20
    • 1970-01-01
    相关资源
    最近更新 更多