如何在 R 中强制 scale_y_datetime 比例显示 24:00 而不是 00:00

How to force scale_y_datetime scale to show 24:00 instead of 00:00 in R

我有以下 data.frame 名为 qq

head(qq)
  my_year  my_time
1    2004 20:08:04
2    2004 10:22:40
3    2004 15:55:26
4    2004 15:54:00
5    2004 07:29:26
6    2004 13:23:16

我想绘制 my_time vs my_year(在这个玩具示例中只有一年)。

ggplot(qq, aes(factor(my_year),
                    as.POSIXct(my_time,
                    format = "%H:%M:%S"))) +
 ggbeeswarm::geom_quasirandom()+
 theme_bw() + xlab("")+
 ylab("Time of the day")+
 scale_y_datetime(breaks = "2 hour",
                  date_labels= "%H:%M")

问题: 如何强制 y 轴从 0:00 到 24:00?在这种情况下,数据不会超过 23:00,但当超过时,y 轴显示 0:00 而不是 24:00。

如果您这样做

,您也可以使用此数据重现此问题

scale_y_datetime(breaks = "1 hour", ...)

如果您想重现问题,请提供以下数据。

dput(qq)
structure(list(my_year = c(2004, 2004, 2004, 2004, 2004, 2004, 
2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 
2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 
2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 
2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 
2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 
2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 
2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 
2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 
2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004), my_time = structure(c(72484L, 
37360L, 57326L, 57240L, 26966L, 48196L, 48047L, 47931L, 71027L, 
78931L, 32144L, 40831L, 31545L, 31092L, 73992L, 39895L, 76988L, 
70303L, 52993L, 77522L, 53289L, 43273L, 52609L, 58788L, 69625L, 
83071L, 60847L, 62218L, 75594L, 58615L, 38332L, 45811L, 75290L, 
3063L, 67321L, 74520L, 74248L, 47665L, 54416L, 33803L, 32515L, 
32428L, 40518L, 61085L, 63825L, 66352L, 73773L, 67165L, 37659L, 
47710L, 49206L, 72484L, 37360L, 57326L, 57240L, 26966L, 48196L, 
48047L, 47931L, 71027L, 78931L, 32144L, 40831L, 31545L, 31092L, 
73992L, 39895L, 76988L, 70303L, 52993L, 77522L, 53289L, 43273L, 
52609L, 58788L, 69625L, 83071L, 60847L, 62218L, 75594L, 58615L, 
38332L, 45811L, 75290L, 3063L, 67321L, 74520L, 74248L, 47665L, 
54416L, 33803L, 32515L, 32428L, 40518L, 61085L, 63825L, 66352L, 
73773L, 67165L, 37659L, 47710L, 49206L), class = "ITime")), class = "data.frame", row.names = c(NA, 
-102L), .Names = c("my_year", "my_time"))

一种方法是放弃 ITime 格式并使用带有小时标签的数字刻度:

qq %>%
  mutate(hour_num = my_time %>% as.integer() %>% `/` (60*60)) %>%
  ggplot(aes(factor(my_year), hour_num)) +
  ggbeeswarm::geom_quasirandom()+
  theme_bw() + xlab("")+
  ylab("Time of the day") +
  scale_y_continuous(breaks = 2*0:12,
                     labels = function(x) {paste0(floor(x),":00")})