创建一个图,突出显示 table 中任何一天按组存在记录的周数

Create a plot which highlight the weeks for which records exists by group for any of the day in table

假设 data.table dt 看起来像这样:

library(data.table)
dt <- data.table(grp = c("01", "01","01", "01", "01", "01", "01", "01", "02", "02", "02",
                     "03", "03", "03",
                     "04", "04", "04", "04"),
             date = c("2012-04-18", "2012-04-19","2012-04-30", "2012-05-10", "2012-06-23", "2012-06-25", 
                      "2012-07-05", "2012-07-06", 
                      "2012-04-07", "2012-04-19", "2012-04-05",
                      "2012-04-04", "2012-04-22", "2012-04-25", 
                      "2012-05-19", "2012-06-05", "2012-06-26", "2012-06-27"))



> dt
    grp       date
 1:  01 2012-04-18
 2:  01 2012-04-19
 3:  01 2012-04-30
 4:  01 2012-05-10
 5:  01 2012-06-23
 6:  01 2012-06-25
 7:  01 2012-07-05
 8:  01 2012-07-06
 9:  02 2012-04-07
10:  02 2012-04-19
11:  02 2012-04-05
12:  03 2012-04-04
13:  03 2012-04-22
14:  03 2012-04-25
15:  04 2012-05-19
16:  04 2012-06-05
17:  04 2012-06-26
18:  04 2012-06-27

我想为每个组创建一个图 grp 突出显示我有记录的周数。我想要这样的图表:

所以我尝试了以下方法,但它只在我有记录的日子里放了一个 |

ggplot(dt) +
   aes(y = grp, x = as.Date(date)) +
   geom_segment(aes(yend = grp, 
                    xend = as.Date(date), 
                    color = grp), 
                size = 6,
                show.legend = FALSE) +
   geom_text(aes(label = grp), 
             nudge_x = 3,
             size = 5) +
   scale_x_date('Date', date_breaks = '7 days', expand = c(0, 2)) +
   scale_color_brewer(palette = 'Set3') +
   theme_bw() +
   theme(axis.line.y = element_blank(),
         axis.text.y = element_blank(),
         axis.ticks.y = element_blank())

现在我的剧情是这样的: 我怎样才能把我的地块改进到我想要的地块?

这对你有用吗?对于 dt 中的每个日期,它会获取它所在的一周的开始和结束。然后它为每个 start/end 周组合绘制一条线段。根据 Henrik 的评论,使用 floor_date/ceiling_date。我需要 as.Date ceiling_date 因为它会将一周四舍五入到第 20 小时所以它 returns class of POSIXct.

library(lubridate)

dt$start_week <- floor_date(as.Date(dt$date), unit = "week")
dt$end_week <- as.Date(ceiling_date(as.Date(dt$date), unit = "week"))

 ggplot(dt, aes(y = grp)) + geom_segment(aes(x = start_week, xend = end_week, yend = grp)) + 
  geom_text(aes(x = as.Date(date), label = grp), nudge_x = 3, size = 5) + 
  theme_bw()+
  theme(axis.text.x=element_text(angle=45,hjust=1,vjust=1))+ 
  scale_x_date('Date', date_breaks = '7 days', expand = c(0, 2)) + 
  scale_color_brewer(palette = 'Set3') + 
  theme(axis.line.y = element_blank(), axis.text.y = element_blank(), axis.ticks.y = element_blank())