【问题标题】:R shift scale at x axis date with a non-continuous sequence of time具有非连续时间序列的 x 轴日期的 R 移位刻度
【发布时间】:2019-09-23 09:26:08
【问题描述】:

我有连续两年(2017-2018)的时间序列数据,从每年 1 月到 12 月。然后我需要绘制从 9 月 17 日到 4 月 18 日的数据。

我可以用一个非常手工制作的代码来完成它,但是我意识到它可以用非常简单的方式完成,现在可以使用用于管理绘图日期的包(包“scales”、“lubridate”等)

有人可以帮我简化我做第二个情节的工作吗? 我会很感激的。

  suppressWarnings(suppressMessages(library("tidyverse", quietly = T)))


  dat <- tibble(
    date = seq(as.Date("2017-01-01"), as.Date("2018-12-31"), by=1),
    var = rgamma(length(date), shape=2, scale=2)) %>% 
    mutate(year = lubridate::year(date),
           month = lubridate::month(date), 
           julian = lubridate::yday(date))
  dat
#> # A tibble: 730 x 5
#>    date         var  year month julian
#>    <date>     <dbl> <dbl> <dbl>  <dbl>
#>  1 2017-01-01 12.9   2017     1      1
#>  2 2017-01-02  6.69  2017     1      2
#>  3 2017-01-03  6.11  2017     1      3
#>  4 2017-01-04  1.68  2017     1      4
#>  5 2017-01-05  1.22  2017     1      5
#>  6 2017-01-06 10.2   2017     1      6
#>  7 2017-01-07  5.13  2017     1      7
#>  8 2017-01-08  4.61  2017     1      8
#>  9 2017-01-09  3.79  2017     1      9
#> 10 2017-01-10  1.11  2017     1     10
#> # … with 720 more rows

  dat %>%
    ggplot() +
    geom_line(aes(julian, var, color = factor(month), linetype=factor(year))) 

  dat %>%
    filter((year == 2017 & month %in% c("9","10", "11", "12"))|
             (year == 2018 & month %in% c("1", "2", "3"))) %>%
    mutate(julian_AWS = ifelse(julian>=244, julian-243, julian+123)) %>% 
    ggplot() +
    geom_line(aes(julian_AWS, var, color = factor(month), linetype=factor(year)))+
    scale_x_continuous(breaks = c(1,#S
                                  31,#O
                                  61,#N
                                  91,#D
                                  121,#E
                                  151,#F
                                  181),#M
                       labels = c("Sep", "Oct", "Nov", "Dec", "Jan", "Feb", "Mar"))+
    theme(axis.text.x=element_text(hjust=-1))

reprex package (v0.2.1) 于 2019 年 5 月 5 日创建

【问题讨论】:

    标签: r date ggplot2


    【解决方案1】:

    我认为您不需要深入研究朱利安日期格式。看看这是否能满足您的需求:

    dat %>%
    filter(date >= '2017-09-01', date < '2018-04-01') %>% 
    ggplot() +
      geom_line(aes(date, var, color = factor(month), linetype = factor(year))) +
      scale_x_date(date_breaks = "1 month", date_labels = "%b") +
      theme(axis.text.x = element_text(hjust = -1))
    
    

    有关日期标签格式的更多信息,请参阅?strftime

    【讨论】:

    • 是的,你是对的,现在我想我没有问正确的问题。因为我也想用它来重叠 2017-2018 年的每日 temp_mean 超过 40 年的 temp_mean 时间序列。那么我将无法通过这种方式过滤平均时间序列数据的数据。也许我会问一个新问题。
    • 非常感谢您能看看这个新问题:stackoverflow.com/questions/55994667/…
    猜你喜欢
    • 2019-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-27
    • 2012-10-15
    • 2020-10-12
    相关资源
    最近更新 更多