【问题标题】:How to plot date interval with event between in R如何在R中绘制日期间隔与事件之间
【发布时间】:2019-09-07 13:43:49
【问题描述】:

我有一个数据框,其 ID 与开始日期、结束日期和另一个对应于前两个日期之间发生的事件相关联。

我想在纵坐标和横坐标上绘制 ID 在所考虑的期间的开始和结束之间有一条线的日期以及事件日期的圆圈(或其他东西)。

几个小时以来我一直在努力寻找合适的解决方案,因此我们将不胜感激任何帮助!


library(tidyverse)

set.seed(2018-11-11)

df <- data_frame(
  ID = c('A', 'B', 'C'),
  begin = seq(as.Date("2017-06-01"), as.Date("2017-08-31"), "1 month"),
  event = seq(as.Date("2018-06-01"), as.Date("2018-08-31"), "1 month"),
  end = seq(as.Date("2020-06-01"), as.Date("2020-08-31"), "1 month")
) 

ggplot(df, aes(x = begin, y = ID, group = ID)) + 
  geom_point() + 
  geom_line()+
  xlab('Dates') +
  ylab('ID')

【问题讨论】:

    标签: r date ggplot2


    【解决方案1】:

    这样的事情怎么样?

    ggplot(df, aes(y=ID, x=event)) + 
    geom_point(color="red") + 
    geom_segment(data=df, aes(x=begin, xend=end, y=ID, yend=ID))+
    xlab('Dates') +
    ylab('ID')
    

    【讨论】:

      【解决方案2】:

      这是一种方法:将数据重新整形为长格式,然后将 ID 放在 y 轴上并为事件添加第二个 geom_points:

      df2 <- reshape2::melt(data = df, variable.name = 'Event', value.name = 'Date')
      
      ggplot(df2, aes(x = Date, y = ID)) + 
         geom_point() + 
         geom_line()+
         geom_point(data = df2 %>% filter(Event == 'event'), color='red', size = 2) +
         xlab('Dates') +
         ylab('ID')
      

      【讨论】:

        【解决方案3】:

        这是你想要的吗:

        library(tidyverse)
        
        set.seed(2018-11-11)
        # data_frame is sort of depreciated (The warning suggested me to use tibble instead)
        
        df <- tibble(
          ID = c('A', 'B', 'C'),
          begin = seq(as.Date("2017-06-01"), as.Date("2017-08-31"), "1 month"),
          event = seq(as.Date("2018-06-01"), as.Date("2018-08-31"), "1 month"),
          end = seq(as.Date("2020-06-01"), as.Date("2020-08-31"), "1 month")
        ) 
        # -------------------------------------------------------------------------
        #df
        # # A tibble: 3 x 4
        #   ID    begin      event      end       
        #   <chr> <date>     <date>     <date>    
        # 1 A     2017-06-01 2018-06-01 2020-06-01
        # 2 B     2017-07-01 2018-07-01 2020-07-01
        # 3 C     2017-08-01 2018-08-01 2020-08-01
        # -------------------------------------------------------------------------
        base <- ggplot(df, aes(x = begin, y = ID))
        
        # add a duration between begin and end using a horizontal segment 
        b_duration <- base + geom_segment(aes(x = begin, xend = end, y = ID, yend=ID), linetype = "dashed", color = "red")
        
        # add a the event date using a circle (point)
        b_duration + geom_point(aes(event), size=4, color = "cyan4") + theme_bw()
        

        输出

        【讨论】:

          猜你喜欢
          • 2011-05-20
          • 2022-01-01
          • 1970-01-01
          • 2020-10-01
          • 2021-12-29
          • 2015-07-18
          • 2018-09-10
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多